Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

push local variables

Tags:

assembly

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


Why are local variables not push into the stack like this:
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
like image 637
chitech Avatar asked Nov 29 '10 20:11

chitech


People also ask

What is a local variable in assembly?

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; }

How are local variables stored on stack?

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.

Where are local variables allocated in C?

. 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.


1 Answers

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).

like image 77
Flinsch Avatar answered Nov 08 '22 00:11

Flinsch