title: Why is so much space allocated on the stack?
body: <p>This question comes from answering Stack Overflow question <em><a href="https://stackoverflow.com/a/15806010/174614">Why do books say, “the compiler allocates space for variables in memory”?</a></em>, where I tried to demonstrate to the OP what happens when you allocate a variable on the stack and how the compiler generates code that knows the size of memory to allocate. Apparently the compiler allocates much more space than what is needed.</p>
  
  <p>However, when compiling the following</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  int main()
  {
      int foo;
      return 0;
  }
  </code></pre>
  
  <p>You get the following assembler output with Visual C++ 2012 compiled in debug mode with no optimisations on:</p>
  
  <pre><code>int main()
  {
  00A31CC0  push        ebp
  00A31CC1  mov         ebp,esp
  00A31CC3  sub         esp,0CCh  // Allocates 204 bytes here.
  00A31CC9  push        ebx
  00A31CCA  push        esi
  00A31CCB  push        edi
  00A31CCC  lea         edi,[ebp-0CCh]
  00A31CD2  mov         ecx,33h
  00A31CD7  mov         eax,0CCCCCCCCh
  00A31CDC  rep stos    dword ptr es:[edi]
     int foo;
     return 0;
  00A31CDE  xor         eax,eax
  }
  </code></pre>
  
  <p>Adding one more <code>int</code> to my program makes the commented line above to the following:</p>
  
  <pre><code>00B81CC3  sub         esp,0D8h // Allocate 216 bytes
  </code></pre>
  
  <p>The question raised by @JamesKanze in my answer linked atop, is why the compiler, and apparently it's not only Visual C++ (I haven't done the experiment with another compiler), allocated 204 and 216 bytes respectively, where in the first case it only needs four and in the second it needs only eight?</p>
  
  <p>This program creates a 32-bit executable.</p>
  
  <p>From a technical perspective, why may it need to allocate 204 bytes instead of just 4?</p>
  
  <p>EDIT:</p>
  
  <p>Calling two functions and creating a <code>double</code> and two <code>int</code> in main, you get</p>
  
  <pre><code> 01374493  sub         esp,0E8h  // 232 bytes
  </code></pre>
  
  <p>For the same program as the edit above, it does this in release mode (no optimizations):</p>
  
  <pre><code> sub    esp, 8                // Two ints
   movsd  QWORD PTR [esp], xmm0 // I suspect this is where my `double` goes
  </code></pre>