Golang / Golang Internals and Memory Management Interview Questions
When does a variable get allocated on the stack versus the heap in Go?
Go does not expose manual heap allocation. Instead, the compiler uses escape analysis to decide, at compile time, whether each variable can live on the current goroutine's stack or must be moved (escape) to the heap.
| Aspect | Stack | Heap |
|---|---|---|
| Lifetime | Function frame — freed on return | Until GC collects (no references) |
| Allocation cost | Near zero (pointer bump) | GC overhead, malloc-like |
| GC involvement | None | Tracked by GC tri-color marking |
| Access speed | Fastest (CPU cache friendly) | Slightly slower (pointer indirection) |
| Size | Default 2 KB, grows dynamically to 1 GB | Limited only by available RAM |
// Does NOT escape â lives on stack (no reference escapes the function) func sum(a, b int) int { result := a + b // stays on stack return result } // DOES escape â caller holds a pointer; Go must allocate on heap func newCounter() *int { n := 0 // n escapes to heap â pointer outlives function frame return &n } // Escape via interface â any value stored in an interface box escapes func logValue(v interface{}) { fmt.Println(v) } x := 42 logValue(x) // x's copy escapes to heap because interface requires a pointer // Slice backing arrays that are too large â compiler heuristic big := make([]byte, 64*1024) // large allocation always goes to heap // Inspect escape analysis // go build -gcflags="-m" ./... // go build -gcflags="-m -m" ./... (verbose, shows reason) // Output lines like: './main.go:8:2: n escapes to heap'
Variables escape to the heap in the following common situations: the address is returned from the function; the variable is stored in a heap-allocated data structure (map, slice, interface); a closure captures it by reference; or the compiler's heuristics decide the stack is too small. Unnecessary heap allocations increase GC pressure — a hot path that constantly allocates small objects is a primary cause of GC-induced latency spikes.
More Related questions...