liveBook · Manning

Stack frame

As explained in 100 Go Mistakes and How to Avoid Them

A stack frame is the runtime record containing a function invocation's local state and associated execution information.

A stack frame is the runtime memory interval created when Go enters a function. It holds that invocation’s local variables and remains accessible only while execution is inside the function. Each goroutine has its own growing, contiguous stack. section 12.5.1

Mistake: treating returned locals as ordinary stack data

Calling sumValue creates a frame containing x, y, and z alongside main’s frame containing a and b. When sumValue returns, its frame is no longer accessible, although its old bytes may remain temporarily. Returning &z therefore requires Go to preserve z outside the ordinary frame lifetime rather than leaving callers with a usable stack address. section 12.5.1

func main() {
    a := 3
    b := 2
 
    c := sumValue(a, b)        #1
    println(c)                 #2
}
 
//go:noinline                  #3
func sumValue(x, y int) int {
    z := x + y
    return z
}

Trace main and sumValue as separate frames: main allocates a and b, sumValue allocates x, y, and z, and returning removes sumValue’s frame from reachable execution state. section 12.5.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces frame creation and retirement through nested calls, stopping short of detailed runtime allocation internals.
Examples
Uses sumValue, sumPtr, stack diagrams, and allocation benchmarks to contrast value and pointer results.
What it assumes
Assumes basic Go functions and pointers while explaining goroutine stacks and frame lifetimes directly.
What you can do after
Evaluate function-local storage and diagnose pointer-lifetime and allocation effects using execution traces and benchmarks.
How it connects
Connects stack frames with goroutines, heap allocation, pointers, function inlining, and memory locality.

Also explained in

Compare how 3 books explain stack frame →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.