Why is so much space allocated on the stack?

This question is based on the answer to the question about stack overflow. Why do books say: "the compiler allocates space for variables in memory"? where I tried to demonstrate the OP what happens when you allocate a variable on the stack and how the compiler generates code that knows the size of the memory to allocate. Apparently, the compiler allocates much more space than necessary.

However, when compiling the following

#include <iostream> using namespace std; int main() { int foo; return 0; } 

You get the following assembler output with Visual C ++ 2012, compiled in debug mode without any optimizations:

 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 } 

Adding another int to my program makes the above comment line as follows:

 00B81CC3 sub esp,0D8h // Allocate 216 bytes 

The question posed by @JamesKanze in my answer linked above is the reason that the compiler, and apparently this is not only Visual C ++ (I did not experiment with another compiler), respectively, 204 and 216 bytes, where in the first case he is only four, and in the second - only eight?

This program creates a 32-bit executable file.

From a technical point of view, why might he need to allocate 204 bytes instead of 4?

EDIT:

By calling two functions and creating a double and two int basically, you get

  01374493 sub esp,0E8h // 232 bytes 

For the same program as for the above, it does this in the release mode (without optimization):

  sub esp, 8 // Two ints movsd QWORD PTR [esp], xmm0 // I suspect this is where my `double` goes 
+62
c ++ compiler-construction
Apr 04 '13 at 8:57
source share
1 answer

This extra space is generated by the / Zi compilation option. That allows Edit + Continue. Additional space is available for local variables, which you can add when editing code during debugging.

You also see the / RTC effect, it initializes all local variables to 0xcccccccc, so it’s easier to diagnose problems due to forgetting to initialize the variables. Of course, none of these codes are generated in the default release configuration settings.

+101
Apr 04 '13 at 9:09 on
source share



All Articles