Course contentsShow
← Rust
Lesson 82 of 1,9102. The Ownership ModelFree lesson

Stack Frames and Execution Contexts

Analyze how local variables are stored and automatically cleared as function calls terminate.

In this lesson, you will learn how Rust manages memory automatically by using a LIFO (Last-In, First-Out) structure called the stack to track your variables.

The Stack Frame

Whenever you call a function in Rust, the program reserves a small block of memory known as a stack frame. This frame acts as a private container for that function's execution context. Inside this container, Rust allocates space for all your local variables, function arguments, and the "return address" (the spot in your code the program should jump back to once the function finishes).

Consider this simple example:

fn main() {
    let x = 10;
    add_five(x);
}

fn add_five(val: i32) {
    let result = val + 5;
    println!("{}", result);
}

When main starts, it gets a stack frame. When you call add_five(x), the CPU pauses main and pushes a new stack frame on top of it. Inside add_five's frame, the variable val (a copy of x) and result are stored.

Automatic Cleanup

The beauty of the stack is how it handles cleanup. Because the stack grows downward (or upward, depending on the architecture) in a strict order, Rust knows exactly when a variable’s life must end.

As soon as add_five finishes executing, the CPU simply "pops" its stack frame off. The memory that held val and result is instantly reclaimed. The program doesn't need to search through memory or run complex garbage collection; it simply moves a pointer back to where main’s frame left off.

This process is what makes Rust’s memory management "zero-cost." You aren't paying a performance penalty to track these variables because the hardware itself handles the stack pointer incrementing and decrementing as part of the function call/return mechanism. Once the function returns, those local variables effectively cease to exist, ensuring that you never try to access data from a context that has already been destroyed.

Key Takeaway: A stack frame is a temporary memory container for a function's local variables that is automatically discarded the moment the function returns.