6.4Stack frames (activation records)
The idea
Every function call pushes a frame holding its parameters, return address and local variables. Returning pops it.
Think of it like this: A stack of trays in a cafeteria: you add a tray for each new task and remove the top one when it is done.
Why it exists
Recursion depth, local-variable lifetime and dangling pointers all follow from how frames are created and destroyed.
How it works
- The caller evaluates the arguments and pushes a new frame.
- The frame stores parameters, a return address and the callee's locals.
- When the function returns, the frame is popped and execution jumps to the return address.
- Too many frames (deep or infinite recursion) overflows the stack.
Worked example: fact(3)
main's frame, then fact(3), fact(2) and fact(1) are stacked, each with its own n. After fact(1) returns, its frame is popped, and so on back to main.
Now play with it
- →Click each box of the frame diagram.
- →Run frames grow and shrink and watch the call stack panel.
Stack while f(3) runs, called from main (grows downward):
locals of f
Variables declared inside f. Created when f is entered, gone when it returns, so they hold garbage until assigned.
Recursion simply stacks more frames of the same function, each with its own parameters and locals, until the base case returns.
Watch the call stack on the right: fact(3) pushes three frames, each with its own n, and they are popped as the calls return.
1#include <stdio.h>2int fact(int n) {3 int r;4 if (n <= 1) return 1;5 r = n * fact(n - 1);6 return r;7}8int main() {9 int v = fact(3);10 printf("%d\n", v);11 return 0;12}
The gold line is the statement about to run.
Call stack (top first)
Output
Call tree so far (indent = recursion depth)
Check yourself
How many stack frames exist at the deepest point of fact(4) (counting main)?
Exam notes (the dense version)
Each call pushes a frame holding the parameters, the return address, the saved frame pointer and the local variables; returning pops it. Frames of the caller stay below. Deep or infinite recursion exhausts the stack (stack overflow). Static and global variables are not in the frame, which is why they survive across calls.
Previous year questions: Storage Classes, Scope & Memory (8)
PYQs are grouped by topic, so this is the full set for Storage Classes, Scope & Memory; try the ones that match this subtopic. Open all 8 on the topic page.