Where will the memory allocation for a string in C will take place
For the C statement given below i would like to know where the memmory allocation will take place.
char* ptr="Hello";//ptr is a automatic variable
then the pointer variable ptr will be allocated on the stack,but where will this string "Hello" be allocated. Is it on Stack or on Heap? And what about memory allocation for initialization statement like char ptr[]="Hello";
The standard doesn't say (it doesn't know about "stack", "heap" etc). But in practice the answer is: Neither. The string literal will be stored in the data section, usually in a read-only page.
As a side note, as Als mentions in the comments, it's undefined behavior to attempt to modify a string literal.
With static strings like in your example, the string is not really allocated. Space for it is made in the executable itself, and the above assignment just sets "ptr" to the address of that space.
I'm not sure if this is implementation dependent or not, but the string is usually in protected memory so you cannot change it ... only point to it.
In UNIX, you can see the static strings in an executable by using the "strings" command on an executable.
链接地址: http://www.djcxy.com/p/80222.html上一篇: 指针指向动态内存分配困惑
下一篇: C中的字符串的内存分配将在哪里发生