C Are string literals created on the stack?

I am a little confused by this expression:

char *s = "abc"; 

Is a string literal being created on the stack?

I know this expression

 char *s = (char *)malloc(10 * sizeof(char)); 

allocates memory on the heap and this expression

 char s[] = "abc"; 

allocates memory on the stack, but I'm completely not sure what the first expression does.

+4
source share
3 answers

Typically, the string literal "abc" is stored in a read-only part of the executable file. The pointer s will be created on the stack (either placed in a register or simply optimized) - and point to this string literal that lives "elsewhere".

+21
source
 "abc" 

String literals are stored in the __TEXT,__cstring (or rodata or whatever the format of the object) section of your program, if the string pool is enabled. This means that it is neither on the stack nor on the heap, but is inserted into the read-only memory area next to your code.

 char *s = "abc"; 

This operator will assign the memory cell of the string literal "abc" to s , i.e. s indicates a read-only memory area.

+6
source

Stacks and heaps are implementation details and are platform dependent (the whole world is not x86). Of the POV language, what is the storage class and degree is important.

String literals have a static extent; the storage for them is allocated at program startup and held until the program terminates. It is also assumed that string literals cannot be changed (trying to do this causes undefined behavior). Contrast this with local variables of scale (auto), whose storage is allocated when the block is written and freed when the block exits. Typically, this means that string literals are not stored in the same memory as block variables.

+3
source

Source: https://habr.com/ru/post/1301347/


All Articles