CodeBlanks Logo Icon CodeBlanks

Escape analysis

Learn how the compiler decides stack vs heap.

Escape analysis

For each variable the compiler asks: can this value still be reached after the function returns? If yes, the value escapes to the heap; if not, it stays on the stack.

func a() *int { x := 1; return &x }  // x escapes to the heap
func b() int  { x := 1; return x }   // x stays on the stack

To see the decisions: go build -gcflags=-m → moved to heap: x.

Common escape causes

Unexpected escapes: passing to functions with any parameters such as fmt.Println(x) (the value is boxed into an interface), slices whose size isn't known at compile time (make([]int, n)), variables captured by closures that outlive the function, and interface method calls. Reading the -gcflags=-m output on hot paths reveals needless heap allocations.

Practice Measure the allocation

Write two functions: isaret() *int returns a local variable's address and deger() int returns its value. Assign the results to package-level variables, measure with testing.AllocsPerRun and print both numbers.

Starter code

main.go
package main

import (
    "fmt"
    "testing"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "testing"
)

var (
    p *int
    v int
)

//go:noinline
func isaret() *int {
    x := 1
    return &x
}

//go:noinline
func deger() int {
    x := 1
    return x
}

func main() {
    a := testing.AllocsPerRun(10, func() { p = isaret() })
    b := testing.AllocsPerRun(10, func() { v = deger() })
    fmt.Println(a, b)
}

Expected output

1 0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which does <strong>not</strong> make a value escape to the heap?

  • Passing its pointer to a goroutine
  • Returning the value by copy Correct answer
  • Returning its address
  • Assigning it to a global

Explanation: Returning a copy gives the caller a new value; the local variable can disappear with the function.

2 Escape report

Question
go build -gcflags=____ ./...
Answer
go build -gcflags=-m ./...

Explanation: -gcflags=-m prints the compiler's escape and inlining decisions.

3 Code and result

Term Meaning
return &x Escapes to heap
return x Stays on stack
make([]int, 8) May stay on stack
make([]int, n) Usually heap

All lessons in Expert