C++, ATT Assembly
I have the following assembly code:
push %ebp
mov %esp, %ebp
sub $0x28, %esp
(...)
My textbook claims that by subtracting 0x28 from the %esp (as part of the formation of the stack), 12 bytes get allocated for variables. Why does subtracting decimal 40 from the stack allocate 12 bytes?
This allocates 40 bytes on the stack. However, there are uses for it other than local variables, so my guess is that the rest is used for alignment and arguments for a future function call.
Since function arguments are also passed on the stack, there needs to be space for any that this function wants to pass to another. It is possible to allocate this space when performing the call by using push
, but it is quite common to allocate the space once at the beginning of the function and just use mov
to place the data in position later. If your function is using 12 bytes for local variables, that leaves up to 28 for function arguments to be used later.
There could also be a little bit extra allocated for alignment. In addition to the alignment of variables mentioned by Jerry, many systems expect the stack pointer to be aligned to a certain value, so this needs to be preserved if you are going to make a function call. On 32-bit systems, this is often 8 bytes, but could also be 16 in this case.
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.
char
local variable will typically still subtract at least 4 from the stack pointer to make room for it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With