I want to know more about the stack. Especially what happens when a function is called with a parameter. To do this, I will write the following code:
#include <stdio.h> int sum(int d, int e, int f){ int result = d + e + f; return result; } int main(void){ int a = 5; int b = 4; int c = 2; int erg = sum(a,b,c); printf("Result is: %d", erg); }
and I get the following Assembly-Code (I will add only part of the main
function because I want to understand this section first):
push ebp, mov ebp, esp and esp, -16 sub esp, 32 mov DWORD PTR[esp+28], 5 mov DWORD PTR[esp+24], 4 mov DWORD PTR[esp+20], 2 mov eax, DWORD PTR[esp+20] mov DWORD PTR[esp+8], eax mov eax, DWORD PTR[esp+24] mov DWORTD PTR[esp+4], eax mov eax, DWORD PTR[esp+28] mov DWORD PTR[esp], eax call sum ........ ........
So, for this part, I draw a little sketch for myself. Take a look, please :) My question is: Where is my ebp
at this moment? Due to line 2 of my assembler code, it should be in the same place as [esp]
, right?
Now, the part of the sum function that follows my second question.
so here is the assembler code:
push ebp mov ebp, esp sub esp, 16 mov eax, DWORD PTR[ebp+12] mov edx, DWORD PTR[ebp+8] mov edx, eax ------------
So, I found out that we can always find our parameters in [eb+12]
and [ebp+8]
. (I skipped the third parameter because I want to keep it simple) So my question is: If I assume that esp
= ebp
and I look at my sketch, I see that in [esp+12]
or now [ebp+12]
there is nothing. But, nevertheless, it is used. How can I imagine this?
Can someone help me? I read so many papers, but no one seems to have sketched these things. Because of this, it is very difficult to understand this.
Thanks!
Here is my sketch:
