6

C++、ATT 程序集

我有以下汇编代码:

push %ebp
mov  %esp, %ebp
sub $0x28, %esp
(...)

我的教科书声称,通过从 %esp 中减去 0x28(作为堆栈形成的一部分),为变量分配了 12 个字节。为什么从堆栈中减去十进制 40 会分配 12 个字节?

4

2 回答 2

5

这会在堆栈上分配 40 个字节。但是,除了局部变量之外,它还有其他用途,所以我猜其余部分用于对齐和未来函数调用的参数。

由于函数参数也在堆栈上传递,因此该函数想要传递给另一个函数的任何参数都需要空间。可以在执行调用时通过 using 分配此空间push,但在函数开始时分配一次空间并mov稍后仅用于将数据放置到位是很常见的。如果您的函数使用 12 个字节作为局部变量,则最多有 28 个字节用于函数参数以供以后使用。

也可能会为对齐分配一些额外的空间。除了 Jerry 提到的变量对齐之外,许多系统都希望堆栈指针与某个值对齐,因此如果您要进行函数调用,则需要保留这一点。在 32 位系统上,这通常是 8 个字节,但在这种情况下也可能是 16 个字节。

于 2013-02-13T05:34:06.710 回答
3

I suspect you may have misread your book, but if you haven't, it looks a great deal to me as if the book is mistaken about this.

Subtracting 40 from the stack pointer allocates 40 bytes. That may not always be precisely correct1, but any deviation from it will usually be pretty small.


  1. For example, if you allocate an 8-byte object in 32-bit code, it could allocate some extra space (12 bytes total) so it can ensure the 8-byte object has 8-byte alignment. Likewise, in 32-bit code you can typically only adjust the stack pointer in (at least) 32-bit increments, so a function that has one char local variable will typically still subtract at least 4 from the stack pointer to make room for it.
于 2013-02-13T05:29:24.980 回答