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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
