开发者

Why did this source code allocate 16 bytes?

(gdb) disas /m main
Dump of assembler code for function main():
2   {
   0x080483f4 <+0>: push   %ebp
   0x080483f5 <+1>: mov    %esp,%ebp
   0x080483f7 <+3>: sub    $0x10,%esp

3       int a = 1;
   0x080483fa <+6>: movl   $0x1,-0x4(%ebp)

4           int b = 10;
   0x08048401 <+13>:    movl   $0xa,-0x8(%ebp)

5           int c;
6           c = a + b;
   0x08048408 <+20>:    mov    -0x8(%ebp),%eax
   0x0804840b <+23>:    mov    -0x4(%ebp),%edx
   0x0804840e <+26>:    lea    (%edx,%eax,1),%eax
   0x08048411 <+29>:    mov    %eax,-0xc(%ebp)

7           return 0;
   0x08048414 <+32>:    mov    $0x0,%eax

8   }
   0x08048419 <+37>:    leave  

Notce the 3rd assembler instruction, it allocated 16 bytes instead of the expected 12 bytes. Why is that? I thought the 3rd line is allocating automatic variables...

Even if I removed the assignment, the allocation is still 16 bytes.

Thanks.


Edit

// no header. nothing
int main()
{
        int a = 1;
        int b = 10;
        int c;
        c = a + b;
        return 0;
}

g++ -g -o demo demo.cpp


Follow up... I read a couple more threads on stack alignment (sorry, I am now studying computer arch and organization class...so I am not familiar with this at all)

Stack Allocation Padding and Alignment

I am supposed it's the compiler's setting. So default, the minimum is 16-byte.

If we have

int a = 1;
int b = 10;
int c = 10;
int d = 10;
// --
int e = 10;

Up to int d, we would have exactly 16-bytes, and the allocation is still 0x10. But when we give another delectation, int e = 10, esp is now allocated 32 bytes (0x20).

This shows me that esp, the stack pointer, is only used for automatic variables.


Follow-开发者_StackOverflow中文版up 2

Call stack and Stack frame

Each stack frame

Storage space for all the automatic variables for the newly called function.

The line number of the calling function to return to when the called function returns.

The arguments, or parameters, of the called function.

But after we allocated int a through int d, it already took us 16 bytes. Main has no function parameters, so that's zero. But the line to return, where did this information go?


I although I haven't seen the source code for main() yet, I believe this is due to stack alignment.

Under your settings, the stack probably needs to be aligned to 8 bytes. Therefore esp is being incremented by 16 bytes rather than 12 bytes. (even though 12 bytes is enough to hold all the variables)

On other systems (with SSE or AVX), the stack will need to be aligned to 16 or 32 bytes.


Nothing mistical - first four bytes are allocated for return code :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜