# What is Stack Frame in C?

«
»
Question: What is Stack Frame in C

Answer: As we know that when one function calls other function, a runtime stack is created for the called function for execution of its instructions, holding automatic variables and other values and return address. Prologue component of called function begins by reserving space for local variables and other values and thus creating the stack frame for the called function. Stack frame is the area on stack which function uses to store local variables and other values. For example, consider a C fragment of code below,

```void sf_fun()
{   /* declarations */

long a1, a2, a3, a4, a5, a6,
a7, a8, a9, a10;

int *pi1, *pi2, *pi3, *pi4, *pi5,
*pi6, *pi7, *pi8, *pi9, *pi10;

/* assignments */

a1 = 10; a2 = 20; a3 = 30; a4 = 40; a5 = 50;
a6 = 60; a7 = 70; a8 = 80; a9 = 90; a10 = 100;

pi1 = (int *)100; pi2 = (int *)110; pi3 = (int *)120; pi4 = (int *)140,
pi5 = (int *)150; pi6 = (int *)160; pi7 = (int *)170; pi8 = (int *)180,
pi9 = (int *)190; pi10 = (int *)200;

}```

And it’s x86-64 bit implementation

```1. sf_fun:
2.       pushq   %rbp           # current value of '%rbp' pushed onto stack
3.       movq    %rsp, %rbp     # copied old stack-pointer to '%rbp'
4.       subq    \$40, %rsp      # reserving 40 bytes on stack
5.       movq    \$10, -8(%rbp)
6.       movq    \$20, -16(%rbp)
7.       movq    \$30, -24(%rbp)
8.       movq    \$40, -32(%rbp)
9.       movq    \$50, -40(%rbp)
movq    \$60, -48(%rbp)
movq    \$70, -56(%rbp)
movq    \$80, -64(%rbp)
movq    \$90, -72(%rbp)
movq    \$100, -80(%rbp)
movq    \$100, -88(%rbp)
movq    \$110, -96(%rbp)
movq    \$120, -104(%rbp)
movq    \$140, -112(%rbp)
movq    \$150, -120(%rbp)
movq    \$160, -128(%rbp)
movq    \$170, -136(%rbp)
movq    \$180, -144(%rbp)
movq    \$190, -152(%rbp)
movq    \$200, -160(%rbp)
leave
ret```

Notice that although function ‘sf_fun()’ hasn’t passed any arguments but has declared several local variables of type ‘long’ and several pointer-to-ints. Then they were assigned with values.

Note: Join free Sanfoundry classes at Telegram or Youtube

Notice instruction no. 4, in assembly code above,

`subq  \$40  %rsp`

which subtracts 40 from current stack-pointer value and allocates 40 bytes for stack for this function. x86-64 bit implementation has a very interesting feature that it allows any program to access up to 128 bytes but to lower addresses to current stack-pointer value. This special area is called ‘red zone’.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials. 