Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How assembly accesses/stores variables on the stack

Tags:

c

stack

assembly

In assembly You can store data in registers or on the stack. Only the top of the stack can be accessed at any given moment (right?). Consider the following C code:

main(){
    int x=2;
    func();
}

func( int x ){
    int i;
    char a;
}

Upon calling func() the following is pushed onto the stack (consider a 32bit system):

variable x (4 bytes, pushed by main)
<RETURN ADDRESS> (4 bytes pushed by main?)
<BASE POINTER> (4 bytes pushed by func())
variable i (4 bytes, pushed by func())
variable a (1 byte, pushed by func())

I have the following questions:

  1. In C code you can access the local variable from anywhere inside the function, but in assembly you can only access the top of the stack. The C code is translated into assembly (in machine code but assembly is the readable form of it). So how does assembly support the reading of variables that are not on top of the stack?

  2. Did I leave out anything that would also be pushed to the stack in my example?

  3. In assembly if you push a char on the stack or an int, how can it determine whethere it needs to push 4 bytes or 1 byte? Because it uses the same operation (push) right?

Thanks in advance Gr. Maricruzz

like image 260
Maricruzz Avatar asked Mar 11 '26 05:03

Maricruzz


1 Answers

The stack pointer at the beginning of the function is put into a register, and then the variables/arguments are accessed via this base address plus the offset for the variable.

If you want to see the code, instead of creating object files, let the compiler stop at creating assembler files. Then you can see exactly how it works. (Of course, that requires you to have a valid C program, unlike the one you have in the question now.)

like image 196
Some programmer dude Avatar answered Mar 13 '26 21:03

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!