Course contentsShow
← Rust
Lesson 209 of 1,9103. Borrowing and ReferencesFree lesson

Visualizing Stack Memory Layout

Diagram the placement of reference variables versus the heap data they point to.

In this lesson, you will learn how to visualize the physical gap between a reference variable living on the stack and the actual data it points to in memory.

The Stack vs. The Pointer

When you create a String or a Vec, Rust allocates the actual content on the heap. However, the variable itself lives on the stack. This stack variable is essentially a "pointer" (or a small struct containing a pointer) that holds the memory address of the heap data.

When you create a reference to that data, you are creating a second variable on the stack that stores the same memory address as the first.

Visualizing the Memory

Imagine we have a String called s1 and a reference r1:

let s1 = String::from("Rust");
let r1 = &s1;

If we look at our computer's memory, it looks like this:

Memory LocationTypeContent (Value)
StackString (s1)[Pointer to Heap, Length, Capacity]
Stack&String (r1)[Memory address of s1]
Heapstr"Rust"

The r1 variable is just a tiny box on the stack containing the "where" of s1. It does not contain the string "Rust" itself. When you use r1, Rust looks at the address stored in the stack, follows that "arrow" to the heap, and retrieves the bytes.

Why this matters

Because r1 is just a pointer sitting on the stack, it is extremely "cheap" to pass around. Whether your String is 5 bytes or 5 gigabytes, the reference on the stack stays the same tiny size (the size of a memory address). This is why Rust encourages passing references: we aren't moving the heap data; we are simply copying a small, fixed-size pointer on the stack to point at the existing data.

Key Takeaway: A reference is simply a small value on the stack that holds a memory address, acting as a bridge to data stored elsewhere in memory.