Reputation: 109
Alo
After I have read about function and stack from http://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames I have a question about local variables.
Snapshot from the article:
push ebp ; save the value of ebp
mov ebp, esp ; ebp now points to the top of the stack
sub esp, 12 ; space allocated on the stack for the local variables
This means local variables can be accessed by referencing ebp. Consider the following C code fragment and corresponding assembly code:
a = 10;
b = 5;
c = 2;
mov [ebp - 4], 10 ; location of variable a
mov [ebp - 8], 5 ; location of b
mov [ebp - 12], 2 ; location of c
Remember that pushing basically does this:
sub esp, 4 ; "allocate" space for the new stack item
mov [esp], X ; put new stack item value X in
push 10
push 5
push 2
instead of
sub esp, 12
mov [ebp - 4], 10 ; location of variable a
mov [ebp - 8], 5 ; location of b
mov [ebp - 12], 2 ; location of c
Upvotes: 8
Views: 13223
Reputation: 4341
It's more a matter of semantics rather than of technical correctness: push
and pop
are used to save and restore registers or values; but providing local variables for a function does not correspond to this regular purpose of push
/pop
. So, the stack is managed manually here (except of push ebp
and pop ebp
, because here we actually want to save and restore ebp
in the true sense of push
/pop
).
Upvotes: 2
Reputation: 21369
Practically speaking, if you know how much stack space you need and reserve it in a single operation you can then use the mov instruction which executes faster than a push immed (especially now that the offset calculation has dedicated hardware). There's also perhaps a legacy component having to do with the fact that push immed didn't become available on the x86 until the release of the 80186/80188 processors. By that time, the sub/mov convention had become a well established pattern.
Upvotes: 3