How C strings are allocated in memory?

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.


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.

Leave a Comment