Understanding Allocations: the Stack and the Heap
summary
Go decides at compile time whether locals live on the stack or heap and never moves them at runtime; taking an address that’s used after return causes an escape so a local like X = 42 returned by reference ends up on the heap, whereas passing a pointer down usually stays on the stack. Three common heap triggers are referenced after return, too large for the stack or unknown size at compile time (eg a 32‑byte slice). Ask the compiler with go build GC flags -M and inspect runtime behavior with pprof and the tracer.
AI-written summary · about
chapters (15)
- 0:00Introduction to allocations
- 0:22Stack vs heap basics
- 1:29Does allocation location matter?
- 3:38Stack memory walkthrough
- 6:26Pointers and stack memory
- 7:50Sharing down stays on stack
- 8:13Sharing up escapes to heap
- 10:45Escape analysis explained
- 12:31Compiler flags for tracking
- 14:38When values go to heap
- 15:46Common heap-allocated values
- 17:09Stack vs heap in slices
- 18:56Key takeaways summary
- 20:20Tools and final advice
- 20:43Q&A on performance vs clarity








