Question

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

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top