了解堆栈分配和对齐堆栈、分配

2023-09-07 03:17:02 作者:绝色

我正在尝试了解堆栈对齐的工作原理,如 什么是堆栈对齐"中所述? 但我很难找到一个小例子来证明上述行为.我正在检查我的函数 foo 的堆栈分配:

I'm trying to understand how stack alignment works as described in what is "stack alignment"? but I have trouble getting a small example to demonstrate the said behaviour. I'm examining the stack allocation of my function foo:

void foo() {
    int a = 0;
    char b[16];
    b[0] = 'a';
}

我用 gcc -ggdb example.c -o example.out 编译了源文件(即没有任何编译器标志),gdb 的汇编程序转储如下:

I compiled the source file with gcc -ggdb example.c -o example.out (i.e without any compiler flags) and the assembler dump from gdb reads:

(gdb) disassemble foo
Dump of assembler code for function foo:
0x08048394 <+0>:    push   %ebp
0x08048395 <+1>:    mov    %esp,%ebp
0x08048397 <+3>:    sub    $0x20,%esp
0x0804839a <+6>:    movl   $0x0,-0x4(%ebp)
0x080483a1 <+13>:   movb   $0x61,-0x14(%ebp)
0x080483a5 <+17>:   leave  
0x080483a6 <+18>:   ret    
End of assembler dump.

我的堆栈是按 16 字节的块分配的(我通过其他几个测试验证了这一点).根据此处的汇编程序转储,已分配 32 个字节,因为 (16