Where will the memory allocation be allocated for a string in C

For the C statement below, I would like to know where the memmory distribution will occur.

char* ptr="Hello";//ptr is a automatic variable 

then the ptr pointer will be allocated on the stack, but where will this "Hello" line be allocated. Is it on the stack or on the heap? What about memory allocation for the initialization instruction, for example char ptr [] = "Hello";

+6
source share
2 answers

The standard does not say (it does not know about the "stack", "heap", etc.). But in practice, the answer is: None. The string literal will be stored in the data section, usually on a read-only page.

As a note, as Als points out in the comments, undefined behavior tries to change a string literal.

+12
source

With static lines, as in your example, the line does not stand out. The space for it is made in the executable file itself, and the above assignment simply sets "ptr" to the address of this space.

I'm not sure if this depends on the implementation or not, but the string is usually in protected memory, so you cannot change it ... point only to it.

On UNIX, you can see static lines in the executable using the string command in the executable.

+3
source

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


All Articles