Search code examples
c++stackheap-memorystack-size

How to identify if an object should be on the stack or not?


I was looking for a rule of thumb for allocating objects on stack or heap in C++. I have found many discussions here on SO. Many people said, it's about the lifetime of an object. If you need more lifetime than the scope of the function, put it in the heap. That makes perfect sense.

But what made me confusing is, many people said, allocate objects to stack if they are small. If objects are big, put it to heap. But none of them said how to identify an object is big or not?

I have the following questions,

  1. How to identify an object is big or not?
  2. What will be the stack maximum size? Each OS will have different stack size?
  3. I have a wrapper class which wraps vector<string>. It will have around 100 items. Will it make a stack overflow if I allocate this class to a stack? I tried this, but it worked perfectly. Not sure I am doing something wrong.

Solution

  • Well firstly vectors (and all the STL container classes) always allocate from the heap so you don't have to worry about that. For any container with a variable size it's pretty much impossible to use the stack.

    If you think about how stack allocation works (at compile time, basically by incrementing a pointer for each object) then it should be clear that vector memory comes from the heap.

    std::vector<int> myInts;
    std::string myString;
    SomeOther Class;
    
    // this memory must come from the heap, there's no way it
    // can now be allocated on the stack since there are other
    // objects and these parameters could be variable
    myString = "Some String";
    myInts.reserve(256);
    

    Unless you are in a recursive function you can place several kilobytes of data on the stack without much worry. Stack-sizes are controlled by the program (not the OS) and the default tends to range from 32kb - 1mb. Most desktop software comes in at the 1mb range.

    Individual objects are almost never a concern. In general they will either be small enough for the stack, or will allocate internally from the heap.

    If objects are local to a function put them on the stack. If not put them on the heap.

    Use the heap for large buffers you allocate for loading/sorting/manipulating data.