Trace stack growth and copying
Trace stack growth and copying
In Go 1.23, a goroutine starts with a small stack that can grow as needed. Compiler-generated checks on applicable function entries compare stack space with a guard; the runtime can allocate a larger stack, copy live stack contents and adjust relevant pointers using metadata. Stacks may also shrink. System stacks and some special functions follow different rules. Growth is implementation behavior, not a guarantee of unlimited recursion. Ordinary Go pointers remain usable; converting an address to uintptr does not preserve pointer tracking or liveness.
package main
import ( "fmt")
//go:noinlinefunc sum(n int, p *int) int { if n == 0 { return *p } v := n return v + sum(n-1, p)}func main() { x := 7 fmt.Println(sum(1000, &x))}The pointer still refers to x through many calls. This verifies value correctness, not proof that a particular stack was copied. The compiler decides whether x escapes. Inspect assembly for recursive calls and stack checks; a runtime trace or aggregate stack memory snapshot can support diagnosis, but does not directly identify a copy of this specific frame.
Expected output:
500507Bound recursion for untrusted depths
package main
import ( "fmt")
func bounded(n, limit int) (int, error) { if n < 0 || limit < 0 || n > limit { return 0, fmt.Errorf("invalid depth") } if n == 0 { return 0, nil } v, e := bounded(n-1, limit-1) return n + v, e}func main() { v, e := bounded(4, 8) fmt.Println(v, e == nil) _, e = bounded(9, 8) fmt.Println(e != nil)}Validate depth before entering recursion. A huge stack can cause a fatal runtime stack overflow, not a recoverable ordinary panic. The limit in this teaching example is deliberately small; for untrusted tree traversal prefer an explicit work list with bounds on total nodes and memory, not depth alone.
Expected output:
10 truetrueTry it locally
Use an iterative sum for 1 through n with n in 0..1000; reject other values. Verify 0, 1000 and a negative input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime allocation 02: Trace stack growth and copying
Check the lesson objective before moving on.
What happens to normal Go pointers into a copied goroutine stack?
What is a safe approach to untrusted recursion?