Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 19: Stack vs Heap, Where Data Lives

You will understand

  • Stack frames, heap allocation, and static data
  • Thin vs fat pointers in Rust
  • Why "String lives on the heap" is incomplete

Reading time

35 min
Reference Diagram

A Running Rust Process: Binary, Stack, and Heap

BINARY / STATIC DATA code, vtables, string literals, `static` items "hello" trait vtable STACK fast, scoped, fixed-size per frame current frame x: i32 = 42 s: String { ptr, len, cap } caller frame return address saved locals stack pointer moves downward / upward with calls HEAP dynamic storage behind owners on the stack String bytes: h e l l o Vec<T> backing buffer Box<Node> allocation owner metadata stays on the stack
The sentence “a `String` lives on the heap” is incomplete. The bytes do. The owner metadata is an ordinary value in a stack frame unless it is itself stored somewhere else.
Pointer Anatomy

Thin Pointers vs Fat Pointers

&str ptr len slice view into UTF-8 bytes &[T] ptr len borrowed view of contiguous elements &dyn Trait data vtable dynamic dispatch needs metadata too
Rust needs size information to lay out values. Fat pointers are how the language carries enough metadata to talk about dynamically sized or dynamically dispatched things without hiding the representation from you.

Readiness Check - Memory Model Reasoning

Use this checkpoint before moving on to move/copy/clone semantics.

SkillLevel 0Level 1Level 2Level 3
Explain stack vs heap accuratelyI confuse value and allocation locationI can describe stack and heap separatelyI can explain where owner metadata and owned bytes liveI can predict layout implications in unfamiliar code
Reason about pointer metadataI treat all references as identical pointersI recognize slices carry extra metadataI can explain thin vs fat pointers correctlyI can use pointer-shape reasoning to debug APIs and errors
Connect memory model to ownershipI memorize facts without transfer reasoningI know ownership controls cleanupI can explain how ownership metadata drives drop behaviorI can design data flow to avoid accidental allocations

Target Level 2+ before continuing to Chapter 20.

Compiler Error Decoder - Memory Layout and Access

Error codeWhat it usually meansTypical fix direction
E0277Type does not satisfy required trait boundEnsure required trait implementations or change API constraints
E0308Type mismatch from wrong data representation assumptionsAlign concrete type (String, &str, slices, trait objects) with API contract
E0609Tried to access field that does not exist on value shapeRe-check whether you have a concrete struct, reference, or trait object

When these appear, inspect the value shape first: ownership, pointer metadata, and concrete type.

Step 1 - The Problem