开发者

C Are string literals created on the stack?

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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜