It is known that when we declare local variables they get stored into stack which is FILO. But I was asked to draw a diagram to show how those variables are getting pushed into stack? Well, I got little confused for the sample code was given:
int giveMe_Red(int *xPos, int *yPos)
{
int count = 0;
int *nextpos, ifTreped;
int loc[8] = {0};
.
.
.
.
return count;
}
Could anyone please help me to understand how every variable get stored into memory, like arrays, pointers etc. Say, "count" in level-0 then "*nextpos" in level-1 of stack or something else. If there is recursion then how they are stored?
The details depend on the processor, but for example in x86 normally the stack space for all variables is allocated at once with a single subtraction to esp.
The standard prologue is
push ebp ; Save old base pointer
mov ebp, esp ; Mark current base pointer
sub esp, stack_space ; Allocate stack space
the epilogue is
mov esp, ebp ; Free stack space
pop ebp ; Reload old base pointer
ret ; Return to caller
In your case the space needed (assuming 32bit and that those are all the locals) would be
countnextPosifTrepedloc arrayfor a total of 44 bytes (+ 4 for the space needed to save ebp).
After the sub esp, 44 there would be the code to zero all elements of loc.
After checking with gcc seems the allocated space is for 48 bytes (not 44), not sure why but possibly for stack alignment reasons.
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