Understanding storage of strings in C++ - Part 1…. Stack or heap?

Heart Bleed
Obscure System
Published in
2 min readAug 3, 2020

Programming in C was very straight forward. At least in terms of memory. We know where the variables are stored. They are not stored in the heap until unless we use malloc/calloc. C++ however have many many classes and libraries that abstract the storage away from the developer. It is good because it takes the burden of the developer from issues like a memory leak, double free, SegFaults, etc. If you need a refresher on the storage, you can refer to the intro section of my Fork vs Thread story.

Stack or Heap?

So are C++ string stored in stack or heap? Well, the answer is “It depends…”. Let understand this with a small example.

The above program is a simple C++ program that stores a string in a variable and prints it out. We also override the new operator. So if the string was allocated in heap the new function should be called and we should see the “Allocated…” message. It the string is stored in the stack, we won't be able to see the “Allocated…” message. We will just see the string that we stored. On compiling and executing the above the code we get,

$ g++ small_string.cpp -o small_string;./small_String 
0123456789

We see that we store a string of length 11 chars(10 + null character). Let’s change the program by increasing the size of the string to 15 characters(16 adding the null char).

The output of the above program is

$ g++ stillsmall_string.cpp -o stillsmall_string;./stillsmall_string 
012345678901234

We still don’t see the “Allocated…” message. Let's increase the string by one more character.

We increase the number of characters to 16(17 adding the null character). The output below shows the “Allocated…” message

$ g++ large_string.cpp -o large_string; ./large_string 
Allocated 17 bytes
0123456789012345

In the above output, we see that the new function we overrode was called, meaning the string was stored in heap.

*So any string above the length 15 is stored in heap.

Conclusion

I added a “*” in the above statement for a reason. The answer to my earlier question “So are C++ string stored in stack or heap? It depends.”, it just does not depend on the length of the string. It depends on the compiler and underlying operating system. The above programs were executed with ubuntu and g++-7.5.0. I was able to see the same results in Mac OS. This length of 15 can vary based on operating systems. In fact, in fedora and red-hat the strings are always stored in heap. They are never stored in the stack.

We saw how the strings are store in stack and heap. In part 2 of the article(Understanding storage of strings in C++ — Part 2: Stack) let’s understand the raw format in which they are stored in the memory.

--

--