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
A local variable holds values for a subroutine while the subroutine is active. For example, in the following function (written in C), b and c are local variables. int mysub( int arg ) { int b, c; b = arg*2; c = b + 7; return c; }
The stack is used for dynamic memory allocation, and local variables are stored at the top of the stack in a stack frame. A frame pointer is used to refer to local variables in the stack frame.
. Local variables are declared within a function and are not visible to other functions. address. The address returned points to a variable which is stored on the program stack.
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
).
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