Codiqo

Learn C · lesson 51 of 60 · about 8 minutes

Tracing and Fixing Recursion

Follow every call step by step, and spot recursion that never stops.

What you'll learn

  • Trace the order of recursive calls
  • Explain what the call stack is
  • Fix a missing or unreachable base case

Boot in order, stop in reverse

For the restart, services have to start in order, network before disk before web, because each one needs the ones before it. Shutting down goes the other way: web first, network last. The report gets that for free from the call stack. boot_services prints Starting before its recursive call, on the way down, and Stopping after it, on the way back up, so the services stop in the reverse of the order they started. The admin types up to 6 service names until end.

The call stack

Every call gets its own copy of its parameters and local variables, stored in a stack frame. When a function calls itself, the first call waits while the new one runs, and its frame stays on the call stack.

When the base case returns, the calls finish one by one, newest first. Code after the recursive call runs on the way back out.

In and out

#include <stdio.h>

void dive(int n) {
    if (n == 0) {
        printf("bottom\n");
        return;
    }
    printf("going down %d\n", n);
    dive(n - 1);
    printf("coming up %d\n", n);
}

int main(void) {
    dive(2);
    return 0;
}

Output

going down 2
going down 1
bottom
coming up 1
coming up 2

When it never stops

If the base case is missing, or the calls never reach it, frames keep piling up until the stack runs out of memory. C doesn't give a friendly message: the program usually just crashes with a segmentation fault. Check that every path makes the problem smaller and that the base case catches the smallest one.

Fibonacci: two calls each time

#include <stdio.h>

int fib(int n) {
    if (n < 2) return n;
    return fib(n - 1) + fib(n - 2);
}

int main(void) {
    for (int i = 0; i < 8; i++) printf("%d ", fib(i));
    printf("\n");
    return 0;
}

Output

0 1 1 2 3 5 8 13

Each frame remembers its own service

boot_services takes the index i of the service it's starting. When it calls itself with i + 1, its own i stays the same in its own frame, so the Stopping line after the call prints the service it started, not the next one.

Open and close

#include <stdio.h>

void nest(int depth, int most) {
    if (depth == most) return;
    printf("open %d\n", depth);
    nest(depth + 1, most);
    printf("close %d\n", depth);
}

int main(void) {
    nest(0, 2);
    return 0;
}

Output

open 0
open 1
close 1
close 0

Tip

fib calls itself twice, so the number of calls doubles quickly: fib(40) makes hundreds of millions of calls. A loop is much faster for that one.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.