riki
riki

Reputation: 2393

How do local variables get stored in stack?

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?

Upvotes: 3

Views: 1807

Answers (2)

user1666959
user1666959

Reputation: 1855

Jonathan's reply is correct, but doesn't answer your question. So let's take the simplest case, assume no optimisation, all arguments are passed on the stack, 32 bit ints, 32 bit addresses, the stack grows downwards, caller cleans up. Before the call to giveme_red is made SP points somewhere. To be able to return from the call you need the return address on the stack, that's four bytes. The two int arguments also go on the stack, 4 bytes each, so SP is now down 12 bytes from its original. Once giveme_red is called more space is needed: four bytes for count, four bytes for the int pointer, four more for 'iftreped' and finally 8 times four bytes for the int array. In order to be able to implement recursion (giveme_red calling itself directly or indirectly through another function) giveme_red will need to set up a new stack frame to call itself. The same sequence as above is repeated. There is usually one more trick, because you need to be able to access your local variables and the arguments another register called BP is usually saved and restored (on the stack). If you want to learn more Aho, Sethi, Ullman, Lam: Compilers (The Dragon Book) is still the standard reference.

Upvotes: 0

6502
6502

Reputation: 114461

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.

Upvotes: 3

Related Questions