CLOSURES & ESCAPE ANALYSIS

When a local variable has to outlive its function

L215 MINCOMPILERS
PREDICT

A closure is a function that uses a variable from the scope around it. for (var i = 0; i < 3; i++) fns.push(() => i); then, after the loop, each function in fns is called. What do they return?

A local variable normally lives in its function’s stack frame, which is popped on return. A closure can keep a reference to a local after that. If the local stayed in the frame, the closure now points at memory the next call will reuse.

Escape analysis finds the locals whose references can outlive the frame and moves only those to the heap. The rest stay on the stack, where allocation is free. The loop bug is the same question one level up: does each iteration get its own variable, or do all closures share one?

▶ SIMULATION
STACK · sp = 0
empty
active frames: none
HEAP
empty
CLOSURES
none yet
every local goes in the stack frame
escape analysisoff
makeCounter allocations0 stack slots · 0 heap boxes
calls returned— (intended 1, 2)
✓ every live reference points at live storage✓ every closure call returns the intended value
SCHEDULE
01[COMPILER]no escape analysis: every local lives in the frame
02[MAKER]call makeCounter(0): allocate start, count, doubled
03[MAKER]create inc = () => ++count, capturing count
04[MAKER]return inc; pop the makeCounter frame
05[OTHER]other() runs: locals flags = 0, total = 99, then returns
06[CALLER]inc() call #1
07[CALLER]inc() call #2
08[CALLER]check the results
Start of stack only scenario. 8 steps.
function makeCounter(start) {
  let count = start;        // in makeCounter's stack frame
  let doubled = start * 2;
  log(doubled);
  return () => ++count;     // closure keeps &count
}                           // frame popped: &count now dangles

for (var i = 0; i < 3; i++) fns.push(() => i);  // one i: 3, 3, 3

Watch the first invariant turn red in STACK ONLY the moment makeCounter returns, two steps before any wrong value appears. ESCAPE ANALYSIS runs the same calls and holds with one heap box; start and doubled stay on the stack. The loop scenarios break and hold the second invariant.

BREAK IT NOT YET

Escape analysis is off: count lives in makeCounter's frame. Order the calls so that inc() returns something other than 1.

GOAL: inc() returns something other than 1

FIX IT NOT YET

Return the set of fn's own locals (params and top-level lets) that must live on the heap under the conservative rule: every one read or written from inside a nested function that does not declare its own variable of that name, and every one whose address is taken. Nothing else: under this rule, boxing any other local is a failure too. (Real escape analysis, such as Go’s, is finer: a closure or address that never leaves the frame stays on the stack.)

Mental model:

a closure captures a variable, not a value. If the variable can be reached after its frame is gone, it has escaped and must live on the heap. Escape analysis is the compiler proving, variable by variable, that most locals don’t escape, so they keep their free stack allocation.

IN PRODUCTION

Go's compiler (go build -gcflags=-m prints “moved to heap”), the JVM's scalar replacement, V8's context allocation for captured variables, Rust's borrow checker rejecting a reference that outlives its frame, and the Go 1.22 loop-variable change.

IN INTERVIEWS

“What does this loop of closures print?” or “Why does returning a pointer to a local work in Go but not in C?” Explain capture by reference, name escape analysis as the reason Go heap-allocates that local, and give the per-iteration binding fix.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: CAPSTONE: A TINY OPTIMIZING PASS →