tags:

views:

215

answers:

3

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.

+19  A: 

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".

nos
and note that you can't modify the string "abc" portably, even if s is a char* and not a char const*.
AProgrammer
Actually using a char * to reference read-only constants is considered deprecated. There's also a compiler warning for it. New software should use const char *
Thorsten79
Are there other parts of the executable besides "read only part of the executable" ? Perhaps "read only memory" is less confusing.
AlexKR
@AlexKR: depends. From the POV of most loaders, the "parts of the executable" are code sections and data sections. Some data sections are read-only (containing for example string literals) others are read-write (containing non-const static variables). All platform-dependent, of course, but the general point is that if you consider RO data to be "part of the executable", then you could also consider RW data to be part.
Steve Jessop
+5  A: 
"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.

KennyTM
+3  A: 

"Stacks" and "heaps" are implementation details and depend on the platform (all the world is not x86). From the language POV, what matters is storage class and extent.

String literals have static extent; storage for them is allocated at program startup and held until the program terminates. It is also assumed that string literals cannot be modified (attempting to do so invokes undefined behavior). Contrast this with local, block-scope (auto) variables, whose storage is allocated on block entry and released on block exit. Typically, this means that string literals are not stored in the same memory as block-scope variables.

John Bode