title: C++: How does the compiler know how much memory to allocate for each stack frame?
body: <p>In the first answer <a href="https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap?lq=1">here</a>, the following was mentioned about the stack memory in C++:</p>
  
  <blockquote>
    <p>When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. </p>
  </blockquote>
  
  <p>This makes perfect sense on the top-level, and makes me curious about how smart compilers are when allocating this memory in and of itself, given the context of <a href="https://stackoverflow.com/questions/2759371/in-c-do-braces-act-as-a-stack-frame?rq=1">this question</a>: Since braces themselves are not a stack frame in C (I assume this holds true for C++ as well), I want to check whether compilers optimize reserved memory based on variable scopes within a single function.</p>
  
  <p>In the following I'm assuming that the stack looks like this before a function call:</p>
  
  <pre><code>--------
  |main()|
  -------- &lt;- stack pointer: space above it is used for current scope
  |      |
  |      |
  |      |
  |      |
  --------
  </code></pre>
  
  <p>And then the following after invoking a function <code>f()</code>:</p>
  
  <pre><code>--------
  |main()|
  -------- &lt;- old stack pointer (osp)
  |  f() |
  -------- &lt;- stack pointer, variables will now be placed between here and osp upon reaching their declarations
  |      |
  |      |
  |      |
  |      |
  --------
  </code></pre>
  
  <p>For example, given this function</p>
  
  <pre><code>void f() {
    int x = 0;
    int y = 5;
    int z = x + y;
  }
  </code></pre>
  
  <p>Presumably, this will just allocate <code>3*sizeof(int)</code> + some extra overhead for bookkeeping.</p>
  
  <p>However, what about this function:</p>
  
  <pre><code>void g() {
    for (int i = 0; i &lt; 100000; i++) {
      int x = 0;
    }
    {
      MyObject myObject[1000];
    }
    {
      MyObject myObject[1000];
    }
  }
  </code></pre>
  
  <p>Ignoring compiler optimizations which may elide a lot of stuff in the above since really they do nothing, I'm curious about the following in the second example:</p>
  
  <ul>
  <li>For the <code>for</code> loop: will the stack space be large enough to fit all 100000 ints?</li>
  <li>On top of that, will the stack space contain <code>1000*sizeof(MyObject)</code> or <code>2000*sizeof(MyObject)</code>?</li>
  </ul>
  
  <p>In general: does the compiler take variable scope into account when determining how much memory it will need for the new stack frame, before invoking a certain function? If this is compiler-specific, how do some well-known compilers do it?</p>