Stack frame lifecycle and local variables
What you'll learn: How your program automatically creates and destroys temporary "workspaces" in memory whenever a function is called.
The Office Desk Analogy
Imagine you work in a large office. Every time you are assigned a new task, you go to an empty area on a massive table (the Stack) and lay down a folder. Inside this folder, you keep your pens, notes, and calculator. While you are working on that task, those tools are right in front of you.
When you finish the task, you don't just put the tools away—you throw the whole folder in the shredder and clear that space on the table. If you need to do the same task again later, you’ll get a brand-new folder and new tools. This folder is what we call a Stack Frame.
The Lifecycle of a Frame
In C, every time you call a function, the computer "pushes" a new frame onto the stack. This frame holds all the local variables defined inside that function.
- Creation: When
my_function()starts, a block of memory is reserved on the stack. - Usage: The function does its work using the variables inside that frame.
- Destruction: As soon as the function hits a
returnstatement or the closing brace}, the frame is "popped" off the stack.
The memory is immediately marked as available for the next function call. This is why local variables are called automatic variables—their lifecycle is managed for you.
Seeing it in Code
Consider how the stack grows and shrinks in this example:
void calculate_total(int price) {
int tax = 5; // Resides in the 'calculate_total' stack frame
int total = price + tax;
// Frame is destroyed here; 'tax' and 'total' vanish
}
int main() {
int item_price = 100; // Resides in the 'main' stack frame
calculate_total(item_price); // A new frame is added on top of main's
return 0;
}
When calculate_total is running, the stack has two frames: one for main at the bottom, and one for calculate_total on top. Once calculate_total finishes, its frame is deleted. The program returns to main, and the memory previously used by tax and total is now considered "junk" or empty space.
Key takeaway
Local variables exist only as long as their function is running; when the function returns, its stack frame is deleted and the memory is reclaimed.