Middle · Memory and runtime
Stack, heap and escape analysis
Does returning a pointer always allocate on the heap?
Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.
Reveal a strong answer
The compiler decides placement from escape analysis and other constraints; source syntax alone does not determine the final allocation. Returning an address is safe because the compiler keeps storage alive as needed.
Inlining and calling context can change escape decisions. Large objects or values passed into opaque interfaces may allocate even when their source appears local. Compiler diagnostics are evidence for a particular build.
Measure allocations with representative benchmarks and inspect go build -gcflags=-m=2 output. Optimize a hot path only after identifying it; do not turn every value into a pointer or introduce unsafe to chase a guess.
Common trap
“Pointers always live on the heap” confuses the pointer value with the object it points to.
Try it
Compare allocations for returning a small struct value and returning its address, with and without inlining.
Worked solution
Benchmark both observable call paths and avoid a discarded-result benchmark that the compiler can eliminate. Use benchmem and compiler output together; do not promise an invariant allocation count across compiler versions.
Change the constraint
What can change when the same function is called through an interface?
How did you do?
Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.
Not marked. Progress stays on this browser, separate from course completion.
Primary references
Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.