So I was recently looking at someone’s code and I saw that the compiler didn’t complain nor were there any run time errors with the following:
const char *p = "I didn't malloc...";
The code above works but I was wondering how. Here is what I think is happening. Can anyone confirm this please?
So “I didn’t malloc…” gets allocated statically on the stack at compile time and the address to that is passed to the pointer p. Similar to how static array’s are allocated. I am 90% sure of this, but some confirmation would help.
Thanks.
That’s a string literal. The standard doesn’t know about “stack”, “heaps” etc – those are implementation details. So there’s no “standard” location.
But typically it’s not on the stack. It’s in a read-only region called
text. And it’s not “similar to how static array’s are allocated“.