What is a Stack Frame?
What you'll learn: Understand how C organizes memory for each individual function call using isolated "frames."
The Office Cubicle Analogy
Imagine a busy office building. When a manager starts a task, they don’t just throw their paperwork onto a giant, messy pile in the lobby. Instead, they assign that task to a specific cubicle. That cubicle holds everything needed for that specific job: the instructions, the local files, and a desk to work on.
In C, a Stack Frame is that cubicle. Every time you call a function, the computer carves out a private slice of memory on the "Call Stack" just for that execution.
What lives inside a frame?
A stack frame is a temporary container that holds three main things:
- Local Variables: Any variable declared inside the function.
- Parameters: The specific values passed into the function (the "inputs").
- The Return Address: A "bookmark" telling the CPU exactly which line of code to jump back to once the function finishes.
Seeing frames in action
Consider this simple code. When main calls square, a brand new frame is "pushed" onto the stack.
#include <stdio.h>
int square(int n) {
int result = n * n; // 'result' and 'n' live in square's frame
return result;
}
int main() {
int x = 5; // 'x' lives in main's frame
int total = square(x);
return 0;
}
When square(x) is called, the computer pauses main and creates a new frame for square. Inside this frame, it stores the value 5 (for n) and space for the result.
Crucially, square cannot see the variable x inside main. It only knows what is inside its own cubicle. This is why local variables are "local"—they are physically trapped inside their specific stack frame.
The "Pop"
When square hits the return statement, its cubicle is dismantled. The memory is "popped" off the stack and cleared away. The CPU looks at the Return Address stored in that frame to find its way back to main and continue where it left off.
Key takeaway
A stack frame is a private block of memory created when a function is called to store its local data, which is automatically destroyed when the function ends.