title: c++ Vector, what happens whenever it expands/reallocate on stack?
body: <p>I'm new to C++ and I'm  using the vector class on my project. I found it quite useful because I can have an array that automatically reallocates whenever it is necessary (ie, if I want to push_back an item and the vector has reached it's maximum capacity, it reallocates itself asking more memory space to the OS), so access to an element of the vector is very quick (it's not like a list, that to reach the "n-th" element I must go through the "n" first elements).</p>
  
  <p>I found <a href="https://stackoverflow.com/questions/8036474/allocating-vectors-memory-on-heap-or-stack">this question</a> very useful, because their answers explained perfectly how the <em>"memory allocator"</em> works when I want to store my vector on the heap/stack:</p>
  
  <pre><code>[1] vector&lt;Type&gt; vect;
  [2] vector&lt;Type&gt; *vect = new vector&lt;Type&gt;;
  [3] vector&lt;Type*&gt; vect;
  </code></pre>
  
  <p>However, a doubt is bugging me for a while, and I can't find its answer:
  Whenever I construct a vector and begin pushing <strong>a lot</strong> of items in, it would reach a moment when the vector would be full, so to continue growing it would need to reallocate, copy itself to a new location and then continue pushing_back items (obviously, this reallocation it's hidden on the implementation of the  class, so it is <em>completely transparent</em> to me)</p>
  
  <p>Fine, if I have created the vector on the heap [2], I have no troubles imagining what may be happening: class vector calls malloc, acquires new space and then copy itself into the new memory and finally deletes the old memory calling free.</p>
  
  <p>However, a veil hides what is happening when I <strong>construct a vector on the stack</strong> [1]: What does it happens when the vector must reallocate? AFAIK, whenever on C/C++ you enter a new function, the computer would look at the declaration of variables and then <strong>expand</strong> the stack to get the necessary space to put these variables, but you can't allocate more space on the stack when the function is already running. How does the class vector solve this problem?</p>