c++heap-memorystack-overflowstdvector

How does nested vectors look like in memory?


So I'm considering making an global nested std::vector (vector <vector <data>> V) initially empty and later during the program, adding data to this nested vector. I'm concerned of adding too much element during run time and exceeding the stack and causing stack overflow.

So after doing some research, my understanding is that the outer vector instance V is an object on the stack that but it's contents such as the inner vector and the elements inside the inner vectors are stored in the heap.

So does that mean I don't have to worry about adding too much elements to the nested vector during runtime since the elements will be stored in the heap and not the stack?
I have a picture of how I think the nested vector V will look in memory below. Please tell me if my current understanding is correct. Thanks

My prediction of nested Vector memory layout: enter image description here

Trying to understand nested vector memory layout and if adding too much elements will cause stack overflow.


Solution

  • std::vector does not use the stack for anything; everything in a vector is in the heap.

    Of course, just in case: if you put the vector on the stack, as in

    void foo()
    {
       std::vector<...> something;
    }
    

    then the actual content will be in the heap as I just said, but there will be a tiny bit of management data that makes up the actual "vector" instance on the stack -- like "pointer to memory block, size of memory block, and number of elements currently used".

    If you do this with a nested vector, as in

    void foo()
    {
       std::vector<std::vector<...>> something;
    }
    

    Then the "outer vector management data" will be on the stack, while the inner vector management data, which is the content-items of the outer vector, are all in the heap.

    if you want to, try something like this:

    #include <vector>
    #include <iostream>
    
    int main()
    {
       std::vector<int> test;
       std::cout << sizeof(test) << '\n';
       for (int i=0; i<10000; i++) test.push_back(i);
       std::cout << sizeof(test) << '\n';
    }
    

    You should be getting a fairly small number as the size of the vector object, and no matter how much you push into it, that won't change. And yes, any C++ "expert" will know that the sizeof() of an object can't change, but a newbie might want to see it not changing :-)