Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do local variables get stored in stack?

Tags:

c

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?

like image 301
Rahul Chakrabarty Avatar asked Feb 13 '26 06:02

Rahul Chakrabarty


1 Answers

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

  • 4 bytes for count
  • 4 for nextPos
  • 4 for ifTreped
  • 4*8 for the loc array

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

EDIT

After checking with gcc seems the allocated space is for 48 bytes (not 44), not sure why but possibly for stack alignment reasons.

like image 198
6502 Avatar answered Feb 15 '26 20:02

6502