Chapter 19: Stack vs Heap, Where Data Lives
Prerequisites
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
A Running Rust Process: Binary, Stack, and Heap
Thin Pointers vs Fat Pointers
Now build the picture one declaration at a time. The simulator below shows exactly where each value lands: a plain integer lives entirely on the stack, while String and Vec split into a stack-resident owner triple and a heap-resident buffer.
Interactive simulation (requires JavaScript): an i32 lives entirely on the stack; String and Vec each store a pointer/length/capacity triple on the stack that points at a heap buffer holding the actual data.
Readiness Check - Memory Model Reasoning
Use this checkpoint before moving on to move/copy/clone semantics.
| Skill | Level 0 | Level 1 | Level 2 | Level 3 |
|---|---|---|---|---|
| Explain stack vs heap accurately | I confuse value and allocation location | I can describe stack and heap separately | I can explain where owner metadata and owned bytes live | I can predict layout implications in unfamiliar code |
| Reason about pointer metadata | I treat all references as identical pointers | I recognize slices carry extra metadata | I can explain thin vs fat pointers correctly | I can use pointer-shape reasoning to debug APIs and errors |
| Connect memory model to ownership | I memorize facts without transfer reasoning | I know ownership controls cleanup | I can explain how ownership metadata drives drop behavior | I can design data flow to avoid accidental allocations |
Target Level 2+ before continuing to Chapter 20.
Compiler Error Decoder - Memory Layout and Access
| Error code | What it usually means | Typical fix direction |
|---|---|---|
| E0277 | Type does not satisfy required trait bound | Ensure required trait implementations or change API constraints |
| E0308 | Type mismatch from wrong data representation assumptions | Align concrete type (String, &str, slices, trait objects) with API contract |
| E0609 | Tried to access field that does not exist on value shape | Re-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.