liveBook · Manning

Heap escape

As explained in 100 Go Mistakes and How to Avoid Them

A heap escape is the allocation of a variable in the heap because it may be referenced after its function returns.

A heap escape occurs when a variable must remain valid after its function returns. If the compiler cannot prove that no later reference exists, it allocates the variable on the shared heap instead of the function's stack. section 12.5.1

Returning a local pointer

Returning &z from sumPtr makes stack allocation unsafe: z would disappear with sumPtr's stack frame, leaving c pointing at an invalid address. Heap allocation preserves z for *c, but adds allocation and garbage-collection cost.

Heap escapes matter because they can change both lifetime and performance:

  • Stack allocation is faster and self-cleaning; heap allocation requires garbage collection and can increase latency. section 12.5.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Traces stack-frame invalidation, shared-heap allocation, garbage collection, and benchmarked costs without detailing compiler escape-analysis internals.
Examples
Uses sumPtr, the returned address of z, invalid-address tracing, and sumValue versus sumPtr benchmarks.
What it assumes
Assumes familiarity with Go functions, pointers, stack frames, goroutines, and garbage collection.
What you can do after
Evaluate pointer-based implementations by tracing lifetimes and measuring allocations, latency, and throughput.
How it connects
Connects stack allocation, heap allocation, pointers, goroutines, garbage collection, and performance benchmarking.

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.