Tracing a Recursive Call Stack

Each active invocation keeps its own local values and the work to resume when a nested call returns.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Write the suspended operation
  2. Read the return path
  3. Record the suspended operation at each depth
  4. Inspect call depth independently of total calls

Write the suspended operation

For a recursive sum where the call at \(n\) returns \(n\) plus the sum at \(n-1\), a call at three waits for two, which waits for one. The call frame stores the relevant local value until the nested result arrives.

Read the return path

With the base result at zero equal to zero, returning yields subtotals one, three, and six. An error may occur either while entering calls or while combining their returned values. Use a hand trace with one column for pending operations.[1]

Record the suspended operation at each depth

For a digit sum in base ten, a call on 314 extracts four and waits for the sum of 31. That call extracts one and waits for the sum of three. Writing return expressions beside the frames shows which pieces remain to be combined. See recursing over digits.

Calls               Suspended work
digits(314)         add 4 to digits(31)
digits(31)          add 1 to digits(3)
digits(3)           add 3 to digits(0)
digits(0)           return 0
Returns             0 → 3 → 4 → 8

Inspect call depth independently of total calls

This trace has four active frames at its deepest point. A branching procedure may make many more total calls while reaching the same maximum depth. Log entries and returns with depth or parent IDs so you can distinguish an unreturned frame from a later sibling.

References

  1. Jeff Erickson, Algorithms ↩