Sub topic 12
Tracing Procedure Calls with a Call Stack
This chapter assumes you can already build a trace table for straight-line code and loops, and that you know how procedures take parameters and return values. Here you extend the trace table so it can follow a program into a procedure call and back out again. The tool for that is the call stack: a pile of records, one for each procedure call that has started and not yet finished.
Why a Flat Trace Table Breaks Down
A trace table with one column per variable works when every name refers to exactly one variable. Procedure calls break that assumption in three ways:
- Two procedures can each have a variable called
x, and these are different variables. - A caller can be partway through evaluating an expression when it calls a procedure. The half-finished result has to be remembered somewhere.
- When a procedure returns, execution has to resume at the exact point where the call was made.
If you trace with one flat row of variables, you end up overwriting the caller's x with the callee's x, or you lose track of where to continue. The call stack fixes all three problems.
The Model: Frames on a Stack
Each call creates a frame, also called an activation record. A frame holds:
- the procedure's parameters, bound to the argument values passed in;
- its local variables;
- the return point, meaning where in the caller execution continues and what the returned value will be used for;
- any pending work in the caller, such as a partial sum that is waiting for this call's result.
The rules are mechanical:
- Call: evaluate the arguments in the caller's frame, push a new frame on top, and bind the parameters.
- Execute: while a procedure runs, only the top frame is active. Names are looked up there.
- Return: compute the return value, pop the top frame, and deliver the value to the return point in the frame that is now on top.
Parameter-Passing Convention
Pseudocode needs a stated rule for what happens when a procedure changes a parameter. This tutorial uses the common convention:
| Parameter kind | Passed as | Effect of changes inside the procedure |
|---|---|---|
| Scalar (number, boolean) | Copy of the value | Invisible to the caller |
| Array | Reference to the same array | Element changes are visible to the caller |
Write the convention at the top of your pseudocode, or mark parameters explicitly, for example PROCEDURE Fill(REF A, n). A trace is only correct if it follows the same convention the program does.
Worked Example: Nested Calls and a Name Clash
FUNCTION Square(x)
RETURN x × x
END FUNCTION
FUNCTION SumSquares(a, b)
s ← Square(a) + Square(b)
RETURN s
END FUNCTION
// main program
x ← 3
y ← SumSquares(x, 4)
OUTPUT yMain has a variable x, and Square has a parameter x. They are separate variables in separate frames.
The Trace
The stack column lists frames from bottom to top, left to right. A ? marks a variable that has not been assigned yet.
step | action | stack (bottom -> top) | pending work
-----+---------------------------------+------------------------------------------------+---------------------------
1 | main: x <- 3 | main{x=3, y=?} | -
2 | call SumSquares(3, 4) | main{x=3, y=?} | SS{a=3, b=4, s=?} | main: y <- [result]
3 | call Square(3) | main | SS{a=3, b=4, s=?} | Sq{x=3} | SS: s <- [result] + Square(b)
4 | Square returns 9; pop | main | SS{a=3, b=4, s=?} | SS: s <- 9 + Square(b)
5 | call Square(4) | main | SS{a=3, b=4, s=?} | Sq{x=4} | SS: s <- 9 + [result]
6 | Square returns 16; pop | main | SS{a=3, b=4, s=?} | SS: s <- 9 + 16
7 | SS: s <- 25 | main | SS{a=3, b=4, s=25} | -
8 | SumSquares returns 25; pop | main{x=3, y=?} | main: y <- 25
9 | main: y <- 25 | main{x=3, y=25} | -
10 | OUTPUT 25 | main{x=3, y=25} | -Some things to check in this trace:
- In step 3,
Square'sxis 3 only becauseahappened to be 3. In step 5 it is 4, while main'sxstays 3 the whole time. - The pending work column records
9 + [result]at step 5. Without it, you would have to re-run the firstSquarecall to find out what the 9 was. - The stack is at most three frames deep, and that happens twice, at steps 3 and 5. The two
Squareframes never exist at the same time.
Worked Example: Value Versus Reference
PROCEDURE Reset(n)
n ← 0
END PROCEDURE
PROCEDURE ClearFirst(A)
A[1] ← 0
END PROCEDURE
// main program
x ← 5
Reset(x)
B ← [5, 6]
ClearFirst(B)
OUTPUT x, Bstep | action | stack (bottom -> top) | shared array
-----+--------------------+-------------------------------------+-------------
1 | x <- 5 | main{x=5} | -
2 | call Reset(5) | main{x=5} | Reset{n=5} | -
3 | n <- 0 | main{x=5} | Reset{n=0} | -
4 | Reset ends; pop | main{x=5} | -
5 | B <- [5, 6] | main{x=5, B=#1} | #1 = [5, 6]
6 | call ClearFirst(B) | main{..., B=#1} | CF{A=#1} | #1 = [5, 6]
7 | A[1] <- 0 | main{..., B=#1} | CF{A=#1} | #1 = [0, 6]
8 | ClearFirst ends | main{x=5, B=#1} | #1 = [0, 6]
9 | OUTPUT 5, [0, 6] | main{x=5, B=#1} | #1 = [0, 6]The array is drawn outside the stack as #1, and both frames point to it. This layout shows why a change made through A is visible through B. When you trace array parameters, keep a separate "shared data" column instead of copying the array into each frame.
Python follows the same convention. Reassigning a parameter rebinds a local name, while changing an element of a list changes the caller's object:
def reset(n):
n = 0
def clear_first(a):
a[0] = 0 # 0-based in Python
x = 5
reset(x)
b = [5, 6]
clear_first(b)
print(x, b) # 5 [0, 6]Common Errors When Tracing Calls
| Error | Symptom in the trace | Fix |
|---|---|---|
| Same-name confusion | The caller's `x` changes after a call that only touched the callee's `x` | Give every frame its own variables, labeled by procedure name |
| Lost pending work | Partial results disappear, or the expression is evaluated twice | Record the pending expression with the slot left for the result |
| Wrong return point | Execution resumes at the top of the caller or at the wrong line | Write the return point when you push the frame |
| Ignored return value | `Square(a)` is called but its result is never used | Make each return arrow end in an assignment or expression in the caller |
| Wrong passing convention | A scalar change "leaks" to the caller, or an array change is lost | State the convention first, and draw arrays as shared data |
| Arguments evaluated in the wrong frame | `Square(a)` uses `Square`'s own variables to compute `a` | Evaluate arguments before pushing the new frame |
How This Prepares You for Recursion
The rules above never asked whether the procedure on top is a different procedure from the one below it. A recursive call follows the same steps. It pushes a new frame for the same procedure with its own copies of the parameters, and that frame pops when the call returns. The next chapter uses this stack model unchanged to trace recursive algorithms.
Exercise
Assume scalars are passed by value. Trace this program with a call stack and give the output. FUNCTION Double(n): n ← n × 2; RETURN n. Main program: n ← 5; m ← Double(n) + n; OUTPUT n, m.
Show answer
Main sets n = 5. Evaluating Double(n) pushes the frame Double{n=5} and records the pending work "m ← [result] + n" in main. Inside Double, the local n becomes 10 and the function returns 10. The frame is popped. Back in main, n is still 5 because only the copy changed, so m = 10 + 5 = 15. The output is 5, 15.
Exercise
Main calls P(2). P(k) calls Q(k + 1) and then R(k). Q(j) calls R(j × 2). R(t) returns t without making any calls. List the stack contents each time a frame is pushed, and state the maximum stack depth, counting main.
Show answer
Push P: main | P{k=2}. Push Q: main | P | Q{j=3}. Push R: main | P | Q | R{t=6}, which is depth 4. R returns 6 and Q returns. Push R: main | P | R{t=2}, which is depth 3. The maximum depth is 4, reached during the call R(6).