Course contentsShow
← C
Lesson 454 of 1,2197. PointersFree lesson

Introduction to the stack frame

Introduction to the stack frame

What you'll learn: How your computer organizes memory for functions using a temporary, self-cleaning storage system called the stack.

The Office Desk Analogy

Imagine your computer's memory is a giant library. When a function starts running, it doesn’t just scatter its data across random shelves. Instead, it behaves like an office worker who clears a specific patch of desk space to work on one specific task.

In C, this "patch of desk space" is called a Stack Frame. Every time you call a function, the computer creates a new frame at the top of the "Stack"—a dedicated region of memory. This frame contains everything that specific function needs: its local variables, its parameters, and the address of where to go back to once the task is finished.

How Frames Stack Up

The "Stack" gets its name because it works exactly like a stack of cafeteria trays. When main() calls functionA(), a new frame for functionA is placed (or "pushed") on top of main. While functionA is running, it can only see and touch its own tray. It doesn't know what's happening in the tray below it.

#include <stdio.h>

void calculate_square(int number) {
    // This variable exists only in the stack frame for calculate_square
    int result = number * number; 
    printf("Result: %d", result);
} // The frame is destroyed (popped) here!

int main() {
    int my_val = 5; // This exists in the stack frame for main
    calculate_square(my_val);
    return 0;
}

Automatic Cleaning

The most powerful feature of the stack frame is its lifespan. When a function hits its closing brace }, its stack frame is instantly "popped" off. The desk space is cleared, and the memory is marked as available for the next function call.

This is why variables created inside a function "die" when the function ends. They lived inside a frame that no longer exists. This automatic management is what makes local variables safe and efficient—you don't have to worry about cleaning up after yourself; the stack does it for you.

Key takeaway

A stack frame is a private, temporary block of memory created when a function is called and automatically destroyed when it finishes.