CLOSURES & ESCAPE ANALYSIS
When a local variable has to outlive its function
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?
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// escapes(makeCounter) = { count }
// count -> heap box (captured by the closure)
// start, doubled -> stack (never referenced after return)
for (let i = 0; i < 3; i++) fns.push(() => i); // fresh i per iteration: 0, 1, 2 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.
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
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.)
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.
“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.