问题
void main(){
int c;
c = function(1, 2);
}
int function(int a, int b){
char buf[10];
a = a+b;
return a;
}
Assembly code:
main:
08048394: push %ebp
08048395: mov %esp,%ebp
08048397: and $0xfffffff0,%esp
**0804839a: sub $0x20,%esp <-----------------------???????**
0804839d: movl $0x2,0x4(%esp)
080483a5: movl $0x1,(%esp)
080483ac: call 0x80483b7 <function>
080483b1: mov %eax,0x1c(%esp)
080483b5: leave
080483b6: ret
function:
080483b7: push %ebp
080483b8: mov %esp,%ebp
080483ba: sub $0x10,%esp
080483bd: mov 0xc(%ebp),%eax
080483c0: add %eax,0x8(%ebp)
080483c3: mov 0x8(%ebp),%eax
080483c6: leave
080483c7: ret
i know aligned by 16-byte,
but, in main(), int c(=4 byte) + 1(4byte) + 2(4byte) in function(1 ,2)
call statement.
so sum of this is 12byte. but by memory aligned, i espect 16byte.
(sub 0x10, %esp)
why sub 0x20, %esp
?
回答1:
Consider this function:
void main(){
int c, d, e, f;
c = function(1, 2, 3, 4);
d =1;
e = 2;
f = 3;
}
Still this will allocate 0x20 space.
But if you add even 1 more local variable or function parameter, it will immediately allocate 0x30 space.
Now consider when there is nothing in the main function, but only one statement:
int c = 1;
Then in this case, it will allocate 0x10 space.
Do you see the pattern here? The system first allocates space for local variable. Then it will allocate space for function parameters. Space allocated is aligned to 0x10.
This is why you see 0x20. 0x10 is for local variables, and another 0x10 is for function parameters.
来源:https://stackoverflow.com/questions/13430540/why-is-0x20-subtracted-from-the-stack-pointer-in-the-prologue-of-this-functions