Question

in this C-code fragment:

void func(void)
{
   int x=10;
   if (x>2)
   {
      int y=2;
      //block statement
      {
         int m=12;
      }
   }
   else
   {
      int z=5;
   }  
}

when does x,y,z and m get allocated and deallocated from func stack frame ?

Was it helpful?

Solution

The actual allocation depends on your compiler, but many compilers allocate space on the stack at the beginning of the function and free it just before the function returns. Note that this is separate from when the variables are actually accessible though, which is just till the end of the block they are defined in.

In your example, with optimization turned on, the compiler is likely not to allocate any space on the stack for your variables and simply return, since it can determine at compile time that the function doesn't actually have any effect.

OTHER TIPS

According to C++ rules, you should think that every local variable is destroyed in the end of its block. This si the time when destructor is called. However, compiler may decide to allocate/deallocate all local variables together in the beginning/end of the function, this is what VC++ compiler does:

void func(void)
{
001413B0  push        ebp  
001413B1  mov         ebp,esp  
001413B3  sub         esp,0F0h  
001413B9  push        ebx  
001413BA  push        esi  
001413BB  push        edi  
001413BC  lea         edi,[ebp-0F0h]  
001413C2  mov         ecx,3Ch  
001413C7  mov         eax,0CCCCCCCCh  
001413CC  rep stos    dword ptr es:[edi]  
    int x=10;
001413CE  mov         dword ptr [x],0Ah  

    if (x>2)
001413D5  cmp         dword ptr [x],2  
001413D9  jle         func+3Bh (1413EBh)  
    {
        int y=2;
001413DB  mov         dword ptr [y],2  
        //block statement
        {
            int m=12;
001413E2  mov         dword ptr [m],0Ch  
        }
    }
    else
001413E9  jmp         func+42h (1413F2h)  
    {
        int z=5;
001413EB  mov         dword ptr [z],5  
    }  
}

But these are implementation details, compiler is free to adjust stack pointer by another way.

So, actual stack pointer adjustment is not defined, but constructor/destructor calls are done exactly according to the function internal blocks. And of course, you cannot use a variable outside its block - this is not compiled. Though stack space may be allocated at this point.

In case of automatic variables (variables declared within a block of code are automatic by default) memory is allocated automatically upon entry to a block and freed automatically upon exit from the block (if you're using c with gcc). You can check this source or this source for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top