54

Here is a function:

void foo() {
   string str = "StackOverflo";
   str.push_back('w');
}

When we declare the string inside the function, is it stored on the Stack or Heap? Why?

string foo() {
   string str = "StackOverflo";
   str.push_back('w');
   return str;
}

Can we return the string reference and continue using somewhere else in the program?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
Andrei Margeloiu
  • 849
  • 2
  • 12
  • 17
  • 13
    Returning reference/pointer to the local variable is an undefined behavior. Your code returns string itself which is perfectly alright – Ari0nhh Feb 05 '17 at 08:05

6 Answers6

57

When we declare the String inside the function, is it stored on the Stack or Heap?

The string object itself is stored on the stack but it points to memory that is on the heap.

Why?

The language is defined such that the string object is stored on the stack. string's implementation to construct an object uses memory on the heap.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 2
    What happens when we return the string from a function? Will it send a copy of the string and the string disappear from the memory? Or will it return a pointer to that memory, and it will disappear? – Andrei Margeloiu Feb 05 '17 at 08:12
  • 3
    @AndreiMargeloiu it will return a copy of std::string, and can be used as long as you store it somewhere. you dont have to worry about its internal data std::string perfectly handles its own data char pointer – Lorence Hernandez Feb 05 '17 at 08:14
  • @AndreiMargeloiu from a conceptual standpoint, the calling function can use the return value to construct a new object, which will use the copy constructor, or assign to an existing object, which will use the copy assignment operator. What happens in those functions is, once again, defined by the `string` class. – R Sahu Feb 05 '17 at 08:15
  • Aham, so it will return a copy of the string, and then the string str will be deleted from the memory? – Andrei Margeloiu Feb 05 '17 at 08:17
  • @AndreiMargeloiu, yes. – R Sahu Feb 05 '17 at 08:18
  • 1
    @AndreiMargeloiu Also look up "copy elision". – user4581301 Feb 05 '17 at 08:20
  • What happens when we return an std::vector? Will the function also return a copy of it(to be received), and the be deleted from the memory? – Andrei Margeloiu Feb 05 '17 at 08:21
  • 1
    @AndreiMargeloiu, yes. If you are able to use C++11, you may find [this article on rvalue references and move semantics](http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html) interesting. – R Sahu Feb 05 '17 at 08:24
  • Please read @Wagner Patriota's answer as the accepted answer does not consider small string optimization. – W.K.S Oct 07 '18 at 17:43
48

The object str (it is the instance of the class std::string) is allocated in the stack. However, the string data itself MAY BE allocated in the heap. It means the object has an internal pointer to a buffer that contains the actual string. However, again, if the string is small (like in this example) usually the string class will have what we call "small string optimization". It means that the size of the std::string object itself is enough to contain the data of the string if it's small enough (usually around 23 bytes + 1 byte for null-terminator)... then if the content is bigger than this, the string data will be allocated in the heap.

Usually you can return your string normally. C++ can handle this for you. The move semantics can take care of whatever necessary here to return the string object pointing to the same string data of the original string, avoiding doing unecessary copies.

Wagner Patriota
  • 5,494
  • 26
  • 49
  • 3
    In addition to move, there is the Return Value optimization: https://en.wikipedia.org/wiki/Copy_elision#Return_value_optimization This way not even a move is necessary, the string may be constructed into the return value. – PaulR Mar 23 '18 at 14:51
  • So why is the content of the string stored on the heap? Why not on the stack? (for large strings) – pooya13 Nov 12 '20 at 17:39
  • 2
    because the stack is much smaller than the heap and it would cause a "stack overflow" – Wagner Patriota Nov 12 '20 at 22:56
  • 1
    @WagnerPatriota Thanks for finally answering the question that was hanging in the air. – Don Slowik Apr 22 '21 at 14:55
10

"StackOverflo", the string literal, is likely stored in the read-only data space of the binary and is mapped into memory when the program starts. You can read more about this here.

str, the class instance`, is allocated on the stack. But the memory its constructor allocates to make a copy of the string literal is allocated on the heap.

The foo function returns a copy of str, so what you have coded is ok.

Community
  • 1
  • 1
selbie
  • 100,020
  • 15
  • 103
  • 173
  • 6
    _But the memory its constructor allocates to make a copy of the string literal is allocated on the heap._ Except if the string is small enough. Then small string optimization might kick in. – besc Feb 05 '17 at 08:16
4

all local variables in C++ are stores in Stack. even local pointers are stored in Stack. but the memory allocated in pointer are stored on Heap.

So, your str is stored in Stack while its value is stored in Heap. because std::string uses char pointer to allocate your "stackoverflow"

Lorence Hernandez
  • 1,189
  • 12
  • 23
  • 4
    Actually, it might be more complex than that. Many C++ implementation have the so called small string optimizations. For some small strings, their content is inside the `string` instance (not on the heap). Details are implementation specific. – Basile Starynkevitch Feb 05 '17 at 08:24
  • 1
    Some systems don't have a stack either – M.M Feb 05 '17 at 09:08
3

On Windows platform, in C++, with std::string, string size less than around 14 char or so (known as small string) is stored in stack with almost no overhead, whereas string size above is stored in heap with overhead. Usually platform and compiler dependent which can be tweaked with optimization options.

std::string myStr {"Hello World"}; // stored in program stack std::string myStr {"StackOverflow saved life of a programmer" }; //pointer is stored in program stack whereas memory for string and is allocated in heap

Below link has good explanation. https://blogs.msmvps.com/gdicanio/2016/11/17/the-small-string-optimization/

userom
  • 403
  • 5
  • 8
3

When we declare the string inside the function is it stored on the Stack or Heap? Why?

The biggest and maybe the only reason to allocate on the heap is to allow string objects to grow in size, for example by calling push_back() or append(). Objects stored on the stack cannot change its size - that's defined by C/C++ language.

F. Müller
  • 3,969
  • 8
  • 38
  • 49