I'm a little bit confused about this expression:
char *s = "abc";
Does the string literal get created on the stack?
I know that 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 totally unsure what the first expression does.
Typically, the string literal "abc"
is stored in a read only part of the executable. The pointer s
would be created on the stack(or placed in a register, or just optimized away) - and point to that string literal which lives "elsewhere".
"abc"
String literals are stored in the __TEXT,__cstring
(or rodata
or whatever depends on the object format) section of your program, if string pooling is enabled. That means, it's neither on the stack, nor in the heap, but sticks in the read-only memory region near your code.
char *s = "abc";
This statement will be assign the memory location of the string literal "abc"
to s
, i.e. s
points to a read-only memory region.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With