Why do books say, “the compiler allocates space for variables in memory”?

前端 未结 7 1600
我在风中等你
我在风中等你 2020-12-31 10:54

Why do books say, \"the compiler allocates space for variables in memory\". Isn\'t it the executable which does that? I mean, for example, if I write the following program

7条回答
  •  暖寄归人
    2020-12-31 11:44

    Technically the act of creating the space itself is done at run time, however the compiler is the one to figure out how much space to reserve on the stack in your case, for your foo variable.

    The compiler knows the size of the int type and therefore can generate the right assembler instruction that will reserve enough space on the stack in order to let foo live there.

    If you look at the below generated assembler (using MSVC2012) for the program you showed, I have commented some of it to show you what happens:

    #include "stdafx.h"
    #include 
    using namespace std;
    
    int main()
    {
    //Setup stack frame for main by storing the stack pointer from the calling function and 
    //reserving space for local variables and storing commonly used registers on the stack
    002E4390  push        ebp  
    002E4391  mov         ebp,esp  
    // reserve space for local variables, which is 204 bytes here, no idea why so much.
    // this is where the compiler calculated the size of your foo and added that to whatever else needs to be stored on the stack. Subtract from stack pointer (esp) because stack grows downward.  
    002E4393  sub         esp,0CCh  
    002E4399  push        ebx  
    002E439A  push        esi  
    002E439B  push        edi  
    002E439C  lea         edi,[ebp-0CCh]  // load effective address of [ebp-0CCh], which I suspect would be your foo variable into edi register
    002E43A2  mov         ecx,33h  
    002E43A7  mov         eax,0CCCCCCCCh  
    002E43AC  rep stos    dword ptr es:[edi]  //fill block of memory at es:[edi] with stuff  
       int foo;
       return 0;
    002E43AE  xor         eax,eax  //set eax to zero for return value
    }
    // restore everything back to how it was before main was called
        002E43B0  pop         edi  
        002E43B1  pop         esi  
        002E43B2  pop         ebx  
        002E43B3  mov         esp,ebp  
        002E43B5  pop         ebp  
        002E43B6  ret  
    

提交回复
热议问题