堆栈分配,为什么会有多余的空间? [英] Stack allocation, why the extra space?

查看:35
本文介绍了堆栈分配,为什么会有多余的空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了更好地掌握调用约定和堆栈的处理方式,我进行了一些尝试,但我不明白为什么 main 在设置堆栈时分配了三个额外的双字(在 <主+0>).它既不与 8 个字节对齐,也不与 16 个字节对齐,所以据我所知,这不是原因.如我所见,main 需要 12 个字节用于 func 和返回值的两个参数.

I was playing around a bit to get a better grip on calling conventions and how the stack is handled, but I can't figure out why main allocates three extra double words when setting up the stack (at <main+0>). It's neither aligned to 8 bytes nor 16 bytes, so that's not why as far as I know. As I see it, main requires 12 bytes for the two parameters to func and the return value.

我错过了什么?

该程序是在 x86 架构上使用gcc -ggdb"编译的 C 代码.

The program is C code compiled with "gcc -ggdb" on a x86 architecture.

我从 gcc 中删除了 -O0 标志,它对输出没有任何影响.

I removed the -O0 flag from gcc, and it made no difference to the output.

(gdb) disas main
Dump of assembler code for function main:
    0x080483d1 <+0>:    sub    esp,0x18
    0x080483d4 <+3>:    mov    DWORD PTR [esp+0x4],0x7
    0x080483dc <+11>:   mov    DWORD PTR [esp],0x3
    0x080483e3 <+18>:   call   0x80483b4 <func>
    0x080483e8 <+23>:   mov    DWORD PTR [esp+0x14],eax
    0x080483ec <+27>:   add    esp,0x18
    0x080483ef <+30>:   ret    
End of assembler dump.

当然我应该发布 C 代码:

Of course I should have posted the C code:

int func(int a, int b) {
    int c = 9;
    return a + b + c;
}

void main() {
    int x;
    x = func(3, 7);
}

平台是 Arch Linux i686.

The platform is Arch Linux i686.

推荐答案

就是对齐.出于某种原因,我假设 esp 会从一开始就对齐,但显然不是.

It's alignment. I assumed for some reason that esp would be aligned from the start, which it clearly isn't.

gcc 默认将堆栈帧对齐到 16 个字节,这就是发生的情况.

gcc aligns stack frames to 16 bytes per default, which is what happened.

这篇关于堆栈分配,为什么会有多余的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆