memtrace

Memory regions

  • Stack Memory
  • Heap Memory
  • Static Memory

Ownership model

  • Ownership & Moves
  • Borrowing & References
Open the Playground
VisualizersStack Memory

Stack Memory

How a function call reserves a stack frame, fills it in, and hands a value back to its caller

What's happening · 01 / 10

Before anything runs

The compiled program has been loaded into memory, but no function has run yet. Nothing is on the stack and nothing is on the heap

Code

1fn main() {
2 let x = 5;
3 let result = foo(x);
4 println!("{result}");
5}
6
7fn foo(input: i32) -> i32 {
8 let y = input + 2;
9 y * 3
10}

Stack Memory

How a function call reserves a stack frame, fills it in, and hands a value back to its caller

HIGH ADDRESSESStackframes and localsHeapBox, String, Vec dataStatic datastatics, string literalsCodecompiled machine codeLOW ADDRESSES
Where this lives in a running program
NEXT CALLformat!(..)s: Stringgreet(name)name: &strmain()n: i32 = 42spSTACK
The idea in one picture

Step by step

Key takeaways

  • Each call pushes a frame that reserves every slot it needs up front
  • A frame holds its return slot, its locals and its arguments
  • Return values are copied back into the caller's frame
  • Popping a frame frees all of it at once

Resources

  • The Rust Book: What is ownership?The stack and heap section is the best short introduction
  • The Rust Book: FunctionsParameters, statements, expressions and return values
  • The unit type ()What a function returns when it declares no return type

Research notes

  • The frame layout here is the conceptual model. Real compilers keep many values in registers, reorder slots, and often inline small functions like foo entirely
  • Threads spawned with std::thread get a 2 MiB stack by default, while the main thread's size is set by the OS (commonly 8 MiB on Linux)
  • Recursing too deeply overflows the stack, and Rust aborts with "thread 'main' has overflowed its stack" instead of corrupting memory
stdoutempty

$cargorun// waiting for the first println!

Auto-play steps