Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much space is allocated by subtracting from %esp in a function call?

Tags:

c++

assembly

att

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?

like image 955
amorimluc Avatar asked Feb 13 '13 05:02

amorimluc


2 Answers

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.

like image 170
ughoavgfhw Avatar answered Oct 26 '22 09:10

ughoavgfhw


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.
like image 33
Jerry Coffin Avatar answered Oct 26 '22 08:10

Jerry Coffin