How C strings are allocated in memory?

c

Solution

When you write

const char *ptr = "blah blah";

then the following happens: the compiler generates a constant string (of type `char []`) with the contents `"blah blah"` and stores it somewhere in the data segment of the executable (it basically has a similar storage duration to that of variables declared using the `static` keyword).

Then, the address of this string, which is valid throughout the lifetime of the program, is stored in the `ptr` pointer, which is then returned. All is fine.

Does this mean that `"blah blah"` is not a local variable inside getString()?

Let me respond with a broken English sentence: yes, it isn't.

However, when you declare an array, as in

const char a[] = "blah blah";

then the compiler doesn't generate a static string. (Indeed, this is a somewhat special case when initializing strings.) It then generates code that will allocate a big enough piece of stack memory for the `a` array (it's not a pointer!) and will fill it with the bytes of the string. Here `a` is actually a local variable and returning its address results in undefined behavior.

So...

But I thought that `const char *ptr` and `const char a[]` were basically the same thing.

No, not at all, because arrays are not pointers.

Problem

Say I have a simple function that returns a C string this way: ``` const char * getString() { const char * ptr = "blah blah"; return ptr; } ``` and I call getString() from main() this way: ``` const char * s = getString(); ``` 1) According to gdb, the variable ptr is stored on the stack, but the string pointed by ptr is not: ``` (gdb) p &ptr $1 = (const char **) 0x7fffffffe688 (gdb) p ptr $2 = 0x4009fc "blah blah" ``` Does this mean that "blah blah" is not a local variable inside getString()? I guess that if it were a local variable, I would not be able to pass it to my main() function... But if it's not, where is it stored? On the heap? Is that a "kind of" dynamically memory allocation implemented by the OS every time it hits on a string, or what? 2) If I use an array instead of a pointer, this way: ``` const char *getString2() { const char a[] = "blah blah blah"; return a; } ``` the compiler warns me that: `warning: address of local variable ‘a’ returned` (and of course the program compiles, but it doesn't work). Actually, if I ask gdb, I get ``` (gdb) p &a $2 = (const char (*)[15]) 0x7fffffffe690 ``` But I thought that const char * ptr and const char a[] were basically the same thing. Looks like they're not. Am I wrong? What is exactely the difference between the two versions? Thank you!

Original source

Related problems