Yes.
And if so, how does the compiler handle it in a valid way? |
String literals are handled specially. They can't really be stored in the actual assembly instructions the way numeric literals are -- so they have to be stored in a separate segment of the exe.
Ultimately, the compiler will take all string literals that exist in your code, and clump them all together in a block of memory, keeping track of which string is where. Then, when you use one of those literals in your code, it will replace the literal with a pointer to wherever it put the actual string data.
So yes, you are correct in that
const char* foo = "bar";
only allocates enough memory for the pointer. And what it actually points to is the segment of memory in the loaded .exe that the literal was placed.
On a side note, this is why you must always use a
const char*
when pointing to literals, and not simply a non-const
char*
. Since, when you are pointing to a literal.... the memory you're pointing to is not modifiable because it's part of the executable program, and not part of allotted heap/stack RAM. And therefore if you try to modify it you will have very bad things happen (typically an access violation/crash).
EDIT: Ninja'd by SGH's much more concise explanation.