Distinguish stack and heap from language rules
Distinguish stack and heap from language rules
Stack storage is associated with execution frames; heap storage is managed by the runtime and garbage collector. Go compilers use escape analysis to help decide where variables can be stored safely. The language does not promise that every local lives on the stack or every new(T) uses the heap.
package main
import ( "fmt")
func localValue(n int) int { p := new(int); *p = n + 1; return *p }func main() { fmt.Println(localValue(4))}This example uses new, but the pointer does not leave localValue. The compiler may avoid heap allocation or even eliminate the variable. The output only establishes the value, not its storage location. Inspect compiler diagnostics with go build -gcflags=-m main.go; messages depend on compiler version and optimization.
Expected output:
5Compare an escaping pointer
package main
import ( "fmt")
func makeValue(n int) *int { v := n + 1; return &v }func main() { p := makeValue(4) fmt.Println(*p)}Here the pointer leaves makeValue; the compiler must ensure the variable remains valid. Inlining may change allocation decisions at the call site. Use measurements such as allocation benchmarks later in the performance chapter before optimizing. Never try to manage ordinary pointer lifetime through guessed addresses.
Expected output:
5Try it locally
Write twice(n int) int using new(int) locally and returning the doubled integer, and twicePtr(n int) *int returning a local doubled value’s address. Print both results for 6. Explain why equal outputs do not establish equal allocations.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pointers and ownership 07: Distinguish stack and heap from language rules
Check the lesson objective before moving on.
Does new(int) guarantee a heap allocation?
What does escape analysis help determine?