计算机科学 · 第 3 册 · 本科一年级

University Computer Science — Year 1

本书暂未推出简体中文版。现有版本:English。

University Computer Science — Year 1 · 本科一年级

3Functions and the Call Stack

The function swap below exchanges its two parameters, and prints them to prove it. Back in main, x is still 1 and y is still 2. The function did its work on copies, which disappeared when it returned. Where those copies lived, how long they lived, and why a function that calls itself a million times can crash a program, is the matter of this chapter: it opens the machine room under every function call.

#include <stdio.h>

void swap(int a, int b)
{
    int t = a;
    a = b;
    b = t;
    printf("inside swap: a = %d, b = %d\n", a, b);
}

int main(void)
{
    int x = 1, y = 2;
    swap(x, y);
    printf("after swap:  x = %d, y = %d\n", x, y);
    return 0;
}
Listing 3.1. A swap that swaps nothing code/bachelor-1/03-c-functions-and-stack/listings/swap_value.c
$ gcc -std=c17 -O2 -Wall -Wextra -o swap_value swap_value.c -lm && ./swap_value
inside swap: a = 2, b = 1
after swap:  x = 1, y = 2
Output 3.1. Swapped inside, unchanged outside.

You already know

A recursive function calls itself on a smaller input and stops at a base case; its correctness is proved by induction on the size of the input. The school volume drew the calls of a recursive Python function as a stack of frames, one per call still running. This chapter shows what those frames are made of in a compiled program, and Chapter 11 returns to the proofs.

3.1 Declaring and defining functions

A C function has a type for each parameter and a type for its result, and the compiler checks every call against them. To do so it must have seen the function’s types before the call: a C file is read once, from top to bottom.

Definition 3.1 (Function declaration, function definition)

A function declaration, or prototype, gives a function’s name, the types of its parameters and the type of its result, followed by a semicolon: int digit_sum(unsigned n);. A function definition gives the same heading followed by the body between braces. A function has exactly one definition in a program, and may be declared many times; every call must come after a declaration or the definition.

A function whose result type is void returns nothing, and a parameter list (void) means “no parameters”. The header files of Chapter 1 are, for the most part, lists of declarations: <stdio.h> declares printf, whose definition is in the C library. The order of definitions in a file matters only through this rule; two functions that call each other need a declaration of the second before the first (Listing 3.5).

Definition 3.2 (Passing by value)

C passes every argument by value: at a call, each argument expression is evaluated and its value is copied into the corresponding parameter, which is a new variable of the called function. An assignment to a parameter changes the copy, never the caller’s variable.

That is the whole story of swap: a and b were copies of x and y. A function hands a value back to its caller through its result; to change a caller’s variable it needs that variable’s address, the subject of Chapter 4. Arrays are the exception that is not one: Chapter 4 shows that the value copied for an array argument is its address.

3.2 The call stack and its frames

When main calls swap, the processor must jump to the code of swap, give it room for a, b and t, and, when swap finishes, come back to the instruction after the call in main with main’s variables intact. All of this is done with one region of memory, the call stack met in Chapter 1.

Definition 3.3 (Call stack, stack frame)

The call stack is a region of memory used last in, first out: each call of a function pushes a stack frame (or activation record) holding what that call needs, and the return pops it. A frame holds the call’s parameters and local variables that do not fit in registers, the registers it must save for its caller, and the return address. Only the frames of calls that have started and not yet returned are on the stack, the most recent on top.

Definition 3.4 (Return address)

The return address of a call is the address of the instruction that follows the call instruction in the caller. The call instruction pushes it on the stack before jumping to the called function, and the function’s final ret instruction pops it and jumps there.

On this machine the conventions are fixed by a document every compiler for 64-bit x86 Linux follows, the System V application binary interface: the call instruction pushes the 8-byte return address, and at the entry of every function the stack pointer, plus 8, is a multiple of 16. On x86-64 the stack grows towards lower addresses: a new frame sits below its caller’s. The program below prints, at each depth of a recursive call, how far below the first call’s local variable the current one lies.

#include <stdint.h>
#include <stdio.h>

static uintptr_t first;

void descend(int depth)
{
    int local = depth;
    uintptr_t here = (uintptr_t)&local;
    if (depth == 0)
        first = here;
    printf("depth %d: local at first - %3lu bytes\n", depth, (unsigned long)(first - here));
    if (depth < 4)
        descend(depth + 1);
}

int main(void)
{
    descend(0);
    return 0;
}
Listing 3.2. Measuring the distance between frames code/bachelor-1/03-c-functions-and-stack/listings/frames.c
$ gcc -std=c17 -O0 -o frames frames.c -lm && ./frames
depth 0: local at first -   0 bytes
depth 1: local at first -  64 bytes
depth 2: local at first - 128 bytes
depth 3: local at first - 192 bytes
depth 4: local at first - 256 bytes
Output 3.2. Built at -O0: each call’s frame is 64 bytes below the previous one.

Each frame of descend takes 64 bytes: the return address (8), the caller’s saved frame pointer (8), and 48 bytes reserved below them, which hold the parameter and the two locals stored at -O0 (16 bytes), an 8-byte guard value that this compiler adds next to the locals of any function that takes a local’s address, and padding that keeps the 16-byte alignment. The printed differences are the same at every run, though the addresses themselves are not; this is why the program prints differences. At -O2 the compiler keeps most variables in registers, and the frames shrink or vanish: a measurement of frames is a measurement of one build.

The stack while swap prints its line, the latest frame at the bottom. The parameters a and b were filled with copies of x and y, then exchanged; main’s variables are untouched. When swap returns, its frame is popped and the processor jumps to the return address.
The stack while swap prints its line, the latest frame at the bottom. The parameters a and b were filled with copies of x and y, then exchanged; main’s variables are untouched. When swap returns, its frame is popped and the processor jumps to the return address.

The figure is a model. At -O2, a, b and t would live in registers and never reach the stack; what is certain is the return address, and the rule that every call that has not returned keeps its frame.

3.3 Recursion on the stack

A recursive call is a call like any other: it pushes a new frame, with new copies of the parameters and locals. Here are three recursive functions on numbers; each stops at a base case and calls itself on a smaller number.

#include <stdio.h>

int digit_sum(unsigned n)               // the sum of the decimal digits of n
{
    if (n < 10)
        return (int)n;                   // base case: one digit
    return digit_sum(n / 10) + (int)(n % 10);
}

void print_binary(unsigned n)            // the binary representation of n
{
    if (n >= 2)
        print_binary(n / 2);             // the leading bits first
    putchar('0' + n % 2);
}

long power(long x, unsigned n)           // x to the n, in about log2(n) calls
{
    if (n == 0)
        return 1;
    long half = power(x, n / 2);
    return n % 2 == 0 ? half * half : half * half * x;
}

int main(void)
{
    printf("digit_sum(2026) = %d\n", digit_sum(2026));
    printf("2026 in binary  = ");
    print_binary(2026);
    printf("\npower(3, 13)    = %ld\n", power(3, 13));
    return 0;
}
Listing 3.3. Digit sum, binary writing and fast power code/bachelor-1/03-c-functions-and-stack/listings/digits.c
$ gcc -std=c17 -O2 -Wall -Wextra -o digits digits.c -lm && ./digits
digit_sum(2026) = 10
2026 in binary  = 11111101010
power(3, 13)    = 1594323
Output 3.3. Three results.

The call digit_sum(2026) pushes frames for 2026, 202, 20 and 2: four frames, one per digit, before the first return. print_binary prints after its recursive call, so the leading bits come out first. power halves its exponent at each call, so power(3, 13) makes five calls (exponents 13, 6, 3, 1, 0), not thirteen. A function that calls itself twice builds a richer structure.

Definition 3.5 (Tree of activations)

The tree of activations (or call tree) of a run has one node per call; the children of a node are the calls made directly by that call, in order. Its root is the first call, its leaves the calls that made no call. The number of calls is the number of nodes; the greatest number of frames on the stack at once is the height of the tree, counted in nodes.

#include <stdio.h>

static int calls = 0;

long binom(int n, int k, int depth)
{
    calls++;
    printf("%*sbinom(%d, %d)\n", 2 * depth, "", n, k);
    if (k == 0 || k == n)
        return 1;                                   // a leaf of the tree
    return binom(n - 1, k - 1, depth + 1) + binom(n - 1, k, depth + 1);
}

int main(void)
{
    long r = binom(4, 2, 0);
    printf("result %ld after %d calls\n", r, calls);
    return 0;
}
Listing 3.4. Printing the tree of activations, one indented line per call code/bachelor-1/03-c-functions-and-stack/listings/calltree.c
$ gcc -std=c17 -O2 -Wall -Wextra -o calltree calltree.c -lm && ./calltree
binom(4, 2)
  binom(3, 1)
    binom(2, 0)
    binom(2, 1)
      binom(1, 0)
      binom(1, 1)
  binom(3, 2)
    binom(2, 1)
      binom(1, 0)
      binom(1, 1)
    binom(2, 2)
result 6 after 11 calls
Output 3.4. Eleven calls, never more than four frames at once.
The tree of activations of binom(4, 2), nodes labelled (n, k), leaves shaded. Thick outlines: the four frames on the stack when the call binom(1, 1) of the right subtree runs, which is a path from the root. The run makes 11 calls, the number of nodes, but needs at most 4 frames, the height.
The tree of activations of binom(4, 2), nodes labelled (n,k)(n, k), leaves shaded. Thick outlines: the four frames on the stack when the call binom(1, 1) of the right subtree runs, which is a path from the root. The run makes 11 calls, the number of nodes, but needs at most 4 frames, the height.

Each leaf returns 1, and every result is a sum of leaf results, so the tree of binom(n, k) has (nk)\binom{n}{k} leaves; being a tree in which every inner node has two children, it has 2(nk)−12\binom{n}{k} - 1 nodes in all (Exercise 3.8). Calls grow like the result, which is huge; the depth is at most n+1n+1. That gap, between the work done and the memory held, is the theme of the weekend problem.

Definition 3.6 (Mutual recursion)

Two or more functions are mutually recursive when each calls another, so that a call of one can lead, through the others, to a call of itself. In C the first one called before its definition must be declared beforehand.

#include <stdbool.h>
#include <stdio.h>

bool is_odd(unsigned n);                 // declared first: is_even calls it

bool is_even(unsigned n)
{
    return n == 0 ? true : is_odd(n - 1);
}

bool is_odd(unsigned n)
{
    return n == 0 ? false : is_even(n - 1);
}

int main(void)
{
    for (unsigned n = 0; n <= 3; n++)
        printf("%u: even %d, odd %d\n", n, is_even(n), is_odd(n));
    return 0;
}
Listing 3.5. Even and odd, each defined through the other code/bachelor-1/03-c-functions-and-stack/listings/even_odd.c
$ gcc -std=c17 -O2 -Wall -Wextra -o even_odd even_odd.c -lm && ./even_odd
0: even 1, odd 0
1: even 0, odd 1
2: even 1, odd 0
3: even 0, odd 1
Output 3.5. Parity by mutual recursion.

Parity is a toy, but mutual recursion is the natural shape of anything defined by a grammar whose rules refer to each other. An arithmetic expression is a sum of terms, a term is a product of factors, and a factor is a digit or a whole expression in parentheses. One function per rule gives an evaluator in which factor calls expr, which calls term, which calls factor.

// evaluator.c: three mutually recursive functions, one per rule of the grammar
//   expr   = term { "+" term }      term = factor { "*" factor }
//   factor = digit | "(" expr ")"
#include "evaluator.h"

static const char *p;                   // the next character to read
static int good;

static long expr(void);

static long factor(void)
{
    if (*p >= '0' && *p <= '9')
        return *p++ - '0';
    if (*p == '(') {
        p++;
        long v = expr();                 // factor calls expr: mutual recursion
        if (*p == ')')
            p++;
        else
            good = 0;
        return v;
    }
    good = 0;
    return 0;
}

static long term(void)
{
    long v = factor();
    while (*p == '*') {
        p++;
        v *= factor();
    }
    return v;
}
Listing 3.6. An evaluator in three mutually recursive functions (the end of the file, expr and evaluate, follows the same pattern) code/bachelor-1/03-c-functions-and-stack/listings/evaluator.c
$ gcc -std=c17 -O2 -Wall -Wextra -o calc calc.c evaluator.c -lm && ./calc
1+2*3        = 7
(1+2)*3      = 9
2*(3+(4*5))  = 46
2*(3+        : syntax error
Output 3.6. Products bind tighter than sums, as the grammar says.

The depth of the recursion follows the nesting of the parentheses: 2*(3+(4*5)) reaches factor three times on one path. The program that evaluates text from a user must therefore ask how deep a call chain can go.

Definition 3.7 (Stack overflow)

The call stack has a maximal size, set when the program starts. A stack overflow happens when a call needs a frame that does not fit in it any more. In C it is not reported by the language: the program writes past the end of the stack region, and the system stops it.

The program below makes each frame about 1 KiB, by giving the function a local array of 1000 bytes, and calls itself until the stack runs out, printing each depth reached into a file. The shell command ulimit -s, covered with the shell in Chapter 8, shows the stack limit of the programs it starts, in KiB, and sets a smaller one; the parentheses keep the change to one command.

#include <stdint.h>
#include <stdio.h>

static uintptr_t top;

void dive(long depth)
{
    volatile char pad[1000];             // make each frame about 1 KiB
    pad[0] = (char)depth;
    if (depth == 0)
        top = (uintptr_t)pad;
    if (depth == 1)
        printf("frame size: %lu bytes\n", (unsigned long)(top - (uintptr_t)pad));
    printf("depth %ld\n", depth);
    fflush(stdout);                      // print now: the crash would lose the buffer
    dive(depth + 1);
    pad[1] = 0;                          // work after the call: no tail call
}

int main(void)
{
    dive(0);
    return 0;
}
Listing 3.7. Going down until the stack runs out code/bachelor-1/03-c-functions-and-stack/listings/deep.c
$ gcc -std=c17 -O0 deep.c -o deep
$ ulimit -s
8192
$ (ulimit -s 512; ./deep > log.txt) 2>/dev/null; echo "exit status $?"
exit status 139
$ head -n 3 log.txt
depth 0
frame size: 1040 bytes
depth 1
$ tail -n 1 log.txt
depth 500
$ for kib in 256 1024 2048; do (ulimit -s $kib; ./deep > log.txt) 2>/dev/null; tail -n 1 log.txt; done
depth 248
depth 1004
depth 2013
Output 3.7. The program was stopped with exit status 139 at each limit; the last depth it reached grows with the limit.

The default limit on this system is 8192 KiB, that is 8 MiB. With 512 KiB and frames of 1040 bytes, the program reached depth 500, and 512×1024/1040≈504.1512 \times 1024 / 1040 \approx 504.1: the stack held the frames we predict, less about two and a half kibibytes used before dive started (the program’s arguments, its environment, the frames of the start-up code and of main). The status 139 is how the system reports a program stopped for touching memory it may not; Chapter 8 explains exit statuses, and the operating-system volume how the stop is delivered. From one run to the next the last depth can differ by a few levels, because the system starts the stack at a slightly random place, and from one machine to another because the environment differs; the run shown turned the randomness off and started the program with an empty environment.

The last depth reached by  for four stack limits. The points lie 3 or 4 levels below the line S/s: the frames that fit in what is left once a constant start-up cost, about 2.5 KiB, is paid. A loop doing the same work would use one frame at every limit.
The last depth reached by Listing 3.7 for four stack limits. The points lie 3 or 4 levels below the line S/sS/s: the frames that fit in what is left once a constant start-up cost, about 2.5 KiB, is paid. A loop doing the same work would use one frame at every limit.

When the last action of a function is a call whose result it returns unchanged, as sum_to does below, that call is a tail call: nothing in the frame is needed after the inner call returns. An optimising compiler may then reuse the frame, turning the recursion into a jump. GCC does it at -O2, not at -O0; the language does not require it, and the Year 2 volume treats the transformation. A program must not count on it.

#include <stdio.h>

long sum_to(long n, long acc)
{
    if (n == 0)
        return acc;
    return sum_to(n - 1, acc + n);       // the call is the last thing done
}

int main(void)
{
    printf("sum = %ld\n", sum_to(10000000, 0));
    return 0;
}
Listing 3.8. A tail-recursive sum code/bachelor-1/03-c-functions-and-stack/listings/sum_to.c
$ gcc -std=c17 -O0 sum_to.c -o sum_O0
$ { ./sum_O0; } 2>/dev/null; echo "exit status $?"
exit status 139
$ gcc -std=c17 -O2 sum_to.c -o sum_O2
$ ./sum_O2; echo "exit status $?"
sum = 50000005000000
exit status 0
Output 3.8. Ten million frames do not fit in 8 MiB; at -O2 there is only one.

3.4 Scope and lifetime

Two different questions are asked about a variable: where in the text its name can be used, and when, during the run, the variable exists. They have different answers, and confusing them causes the bug at the end of this section.

Definition 3.8 (Scope, shadowing)

The scope of a name is the part of the program text where it refers to a given declaration. A name declared inside a block (between braces, or in the parentheses of a for) has block scope: from its declaration to the end of the block. A name declared outside every function has file scope: from its declaration to the end of the file. A declaration in an inner block shadows a declaration of the same name in an enclosing scope: inside the inner block, the name refers to the inner declaration.

#include <stdio.h>

int level = 1;                           // global: file scope

void show(void)
{
    printf("in show:     level = %d\n", level);
}

int main(void)
{
    int level = 2;                       // hides the global inside main
    {
        int level = 3;                   // hides main's level inside this block
        printf("inner block: level = %d\n", level);
    }
    printf("in main:     level = %d\n", level);
    show();
    return 0;
}
Listing 3.9. One name, three variables code/bachelor-1/03-c-functions-and-stack/listings/shadow.c
$ gcc -std=c17 -O2 -Wall -Wextra -o shadow shadow.c -lm && ./shadow
inner block: level = 3
in main:     level = 2
in show:     level = 1
Output 3.9. Each use finds the nearest enclosing declaration in the text.

show sees the global level, not main’s: scope is a property of the text, not of who called whom. Shadowing is legal and almost always a mistake waiting to happen; -Wshadow warns about it.

Definition 3.9 (Lifetime; automatic, static and global variables)

The lifetime (or storage duration) of a variable is the part of the run during which it exists and keeps its value. An automatic variable, a parameter or a local declared without static, lives from the entry into its block to the exit from it, in the current frame; each call has its own. A static variable, a local declared with static, has block scope but lives for the whole run, in the data segment, and is initialised once, before main starts. A global variable, declared at file scope, also lives for the whole run, and its name is visible to the whole file.

#include <stdio.h>

void visit(void)
{
    static int visits = 0;               // created once, before main
    int fresh = 0;                       // created at each call
    visits++;
    fresh++;
    printf("visits = %d, fresh = %d\n", visits, fresh);
}

int main(void)
{
    visit();
    visit();
    visit();
    return 0;
}
Listing 3.10. A static local counts the calls code/bachelor-1/03-c-functions-and-stack/listings/counter_static.c
$ gcc -std=c17 -O2 -Wall -Wextra -o counter_static counter_static.c -lm && ./counter_static
visits = 1, fresh = 1
visits = 2, fresh = 1
visits = 3, fresh = 1
Output 3.10. visits survives the calls, fresh does not.

Definition 3.10 (Internal linkage)

A function or a variable declared at file scope with static has internal linkage: its name is local to its file, and the linker never matches it with a name of another file. Without static, a file-scope name has external linkage: it is visible to the linker, as the global symbols of Chapter 1.

The word static thus means two things, depending on where it is written: inside a function it changes the lifetime; at file scope it changes the linkage. In the evaluator, p, good, factor, term and expr are static: helpers that no other file needs, which cannot then collide with another file’s expr. A module shows the rest of the program only what it declares in its header, a practice Chapter 7 makes systematic.

Lifetimes along a run. Global and static variables exist from start to end. An automatic variable exists once per call (two calls, two separate lives), a block’s local only inside its block. An address returned from a call outlives the variable it names.
Lifetimes along a run. Global and static variables exist from start to end. An automatic variable exists once per call (two calls, two separate lives), a block’s local only inside its block. An address returned from a call outlives the variable it names.

The last line of the figure is a classic bug. A function that returns the address of one of its automatic variables returns the address of something that ceases to exist at the return; its frame will be reused by the next call.

#include <stdio.h>

int *make_counter(void)
{
    int count = 42;
    return &count;                       // count dies when the function returns
}

int main(void)
{
    int *c = make_counter();
    printf("the returned address is %p\n", (void *)c);
    return 0;
}
Listing 3.11. Returning the address of a local code/bachelor-1/03-c-functions-and-stack/listings/dangling_local.c
$ gcc -std=c17 -O2 -Wall -Wextra -o dangling_local dangling_local.c -lm && ./dangling_local
dangling_local.c: In function 'make_counter':
dangling_local.c:7:12: warning: function returns address of local variable [-Wreturn-local-addr]
    7 |     return &count;                       // count dies when the function returns
      |            ^~~~~~
the returned address is (nil)
Output 3.11. GCC warns, then returns a null address.

Using the dead variable is undefined behaviour, and GCC, knowing this, chose to return the null address, which no object has: a later use crashes at once instead of reading garbage. Another compiler may return the stale address. The fix is to return a value, or an object whose lifetime the caller controls: a static variable, a variable of the caller passed by address (Chapter 4), or a block of the heap (Chapter 5).

History — The stack before C

The first versions of Fortran gave each function fixed places for its variables, so a function could not call itself: a second call would have overwritten the first one’s values. Algol 60 let a procedure call itself, which needs a fresh activation record for each call, kept on a stack. C, like most languages since, compiles every call that way.

3.5 Exercises

Exercise 3.1 ★

Predict the line printed by the program below, and explain the compiler’s warning.

#include <stdio.h>

void reset(int x)
{
    x = 0;
}

int reset_and_return(int x)
{
    x = 0;
    return x;
}

int main(void)
{
    int a = 5, b = 5;
    reset(a);
    b = reset_and_return(b);
    printf("a = %d, b = %d\n", a, b);
    return 0;
}
Listing 3.12. Two resets code/bachelor-1/03-c-functions-and-stack/listings/exo_reset.c
Solution

Solution of Exercise 3.1.

reset sets its own copy of a to 0, and the copy dies at the return: a stays 5. The compiler noticed that the parameter is written and never read again, which is the sign of a function that does nothing. reset_and_return returns 0, and main stores it into b.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_reset exo_reset.c -lm && ./exo_reset
exo_reset.c: In function 'reset':
exo_reset.c:4:16: warning: parameter 'x' set but not used [-Wunused-but-set-parameter]
    4 | void reset(int x)
      |            ~~~~^
a = 5, b = 0
Output 3.15. The output.

Exercise 3.2 ★

Predict the two lines printed, naming for each use of x the declaration it refers to.

#include <stdio.h>

int x = 10;

int f(int x)
{
    x = x + 1;
    {
        int x = 100;
        x++;
    }
    return x;
}

int main(void)
{
    int y = f(x);
    printf("%d %d\n", x, y);
    for (int x = 0; x < 2; x++)
        printf("%d ", x);
    printf("%d\n", x);
    return 0;
}
Listing 3.13. Which x? code/bachelor-1/03-c-functions-and-stack/listings/exo_shadow.c
Solution

Solution of Exercise 3.2.

In f(x), the argument is the global x (10); inside f, x is the parameter, which becomes 11; the block’s x = 100 shadows it and dies with the block; f returns 11. In main, the first x printed is the global, 10. The for declares its own x, whose scope is the loop: it prints 0 and 1; after the loop, x is the global again.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_shadow exo_shadow.c -lm && ./exo_shadow
10 11
0 1 10
Output 3.16. The output.

Exercise 3.3 ★

Predict the three numbers printed.

#include <stdio.h>

int add(int amount)
{
    static int total = 100;
    int before = total;
    total += amount;
    return before;
}

int main(void)
{
    int a = add(5);
    int b = add(10);
    int c = add(-20);
    printf("%d %d %d\n", a, b, c);
    return 0;
}
Listing 3.14. A total kept between calls code/bachelor-1/03-c-functions-and-stack/listings/exo_static.c
Solution

Solution of Exercise 3.3.

total is initialised once, to 100, and keeps its value between calls; each call returns the value before its addition: 100, then 105, then 115 (and total ends at 95).

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_static exo_static.c -lm && ./exo_static
100 105 115
Output 3.17. The output.

Exercise 3.4 ★

Draw the call stack at the moment the marked line runs for the second time: which frames are present, in which order, and what values do their parameters and locals hold? Which return address does the top frame hold?

int scale(int v, int factor)
{
    int r = v * factor;
    return r;                            // <-- here, the second time
}

int area(int w, int h)
{
    int s = scale(w, h);
    return s;
}

int main(void)
{
    int a = area(3, 4);
    int b = scale(a, 2);
    return b == 24 ? 0 : 1;
Listing 3.15. Frames at a marked line code/bachelor-1/03-c-functions-and-stack/listings/exo_frames.c
Solution

Solution of Exercise 3.4.

The first time, scale(3, 4) runs from area. The second time is the call scale(a, 2) of main; area has returned and its frame is gone. From the bottom of the stack: the frame of main (a = 12, b not yet assigned), then the frame of scale (v = 12, factor = 2, r = 24). The return address in the top frame points into main, to the instruction that stores the result into b.

Exercise 3.5 ★★

The program below prints greeting: (null). Explain why, using the warning, and give two correct versions of greeting.

#include <stdio.h>

char *greeting(const char *name)
{
    char text[32];
    snprintf(text, sizeof text, "Hello, %s!", name);
    return text;
}

int main(void)
{
    char *g = greeting("Ada");
    printf("greeting: %s\n", g);
    return 0;
}
Listing 3.16. A greeting built in a local array code/bachelor-1/03-c-functions-and-stack/listings/exo_name.c
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_name exo_name.c -lm && ./exo_name
exo_name.c: In function 'greeting':
exo_name.c:8:12: warning: function returns address of local variable [-Wreturn-local-addr]
    8 |     return text;
      |            ^~~~
greeting: (null)
Output 3.12. The warning and the result.
Solution

Solution of Exercise 3.5.

text is an automatic array of greeting: it dies when greeting returns, so the returned address names nothing, and using it is undefined behaviour. GCC warned, then returned the null address; the C library’s printf prints (null) for a null string, a courtesy that the standard does not promise. Two correct versions: declare static char text[32];, which lives for the whole run (but each call overwrites the previous greeting); or let the caller provide the room, with void greeting(const char *name, char *out, size_t size) writing into out by snprintf(out, size, ...).

Exercise 3.6 ★★

The function steps counts the steps from n down to zero, by twos. What happens for steps(7)? Describe the chain of calls, say what the program does at -O0, and correct the base case so that steps is defined for every n ≥0\geq 0.

#include <stdio.h>

int steps(int n)
{
    if (n == 0)
        return 0;
    return 1 + steps(n - 2);
}

int main(void)
{
    printf("steps(10) = %d\n", steps(10));
    printf("steps(7)  = %d\n", steps(7));
    return 0;
Listing 3.17. Down by twos code/bachelor-1/03-c-functions-and-stack/listings/exo_steps.c
Solution

Solution of Exercise 3.6.

steps(7) calls steps(5), steps(3), steps(1), steps(-1), steps(-3), …: the argument jumps over 0 and the base case is never reached. At -O0 every call pushes a frame, and the program is stopped by a stack overflow after a few hundred thousand calls (status 139). At -O2 the compiler may turn the recursion into a loop, which would then run until n - 2 overflows, an undefined behaviour. The fix is to stop at every n ≤0\leq 0: if (n <= 0) return 0;. Then steps(n) =⌈n/2⌉= \lceil n/2 \rceil for n≥0n \geq 0, and steps(7) =4= 4.

Exercise 3.7 ★★

Write int digit_sum_iter(unsigned long long n), a version of digit_sum with a loop instead of recursion, and state a loop invariant that shows it computes the same value. How many frames does it use for a 20-digit number?

Solution

Solution of Exercise 3.7.

The loop keeps the invariant: sum plus the digit sum of the current n equals the digit sum of the original number. It holds at the start (sum is 0), each turn moves the last digit from n to sum, and at the end n is a single digit, its own digit sum. One frame, whatever the number of digits (tested in tests/digit_sum_iter_test.c):

int digit_sum_iter(unsigned long long n)
{
    int sum = 0;
    while (n >= 10) {                    // invariant: sum + digit_sum(n) is the answer
        sum += (int)(n % 10);
        n /= 10;
    }
    return sum + (int)n;
}
The digit sum by a loop code/bachelor-1/03-c-functions-and-stack/exercises/digit_sum_iter.c

Exercise 3.8 ★★

Prove that the naive binom(n, k) of Listing 3.4 makes exactly 2(nk)−12\binom{n}{k} - 1 calls, for 0≤k≤n0 \leq k \leq n. Deduce the number of calls for binom(30, 15), given that (3015)=155 117 520\binom{30}{15} = 155\,117\,520.

Solution

Solution of Exercise 3.8.

Let C(n,k)C(n, k) be the number of calls. By induction on nn. If k=0k = 0 or k=nk = n the call is a leaf: C=1=2(nk)−1C = 1 = 2\binom{n}{k} - 1. Otherwise 0<k<n0 < k < n, and the call makes two calls whose arguments satisfy the hypothesis: C(n,k)=1+C(n−1,k−1)+C(n−1,k)=1+2(n−1k−1)−1+2(n−1k)−1=2(nk)−1C(n, k) = 1 + C(n-1, k-1) + C(n-1, k) = 1 + 2\binom{n-1}{k-1} - 1 + 2\binom{n-1}{k} - 1 = 2\binom{n}{k} - 1 by Pascal’s rule. For binom(30, 15): 2×155 117 520−1=310 235 0392 \times 155\,117\,520 - 1 = 310\,235\,039 calls, to compute a number that a table of 31 rows gives in under 500 additions. The test tests/binom_test.c checks the formula for every n≤20n \leq 20.

Exercise 3.9 ★★

Trace the calls made by is_odd(7) in the program below and give its output. What would is_odd(-1) do?

#include <stdbool.h>
#include <stdio.h>

bool is_odd(int n);

bool is_even(int n)
{
    printf("is_even(%d) ", n);
    return n == 0 ? true : is_odd(n - 1);
}

bool is_odd(int n)
{
    printf("is_odd(%d) ", n);
    return n == 0 ? false : is_even(n - 1);
}

int main(void)
{
    bool r = is_odd(7);
    printf("\nresult %d\n", r);
    return 0;
}
Listing 3.18. Parity with a trace code/bachelor-1/03-c-functions-and-stack/listings/exo_parity.c
Solution

Solution of Exercise 3.9.

Each call prints its name, then calls the other function on n−1n - 1, until is_even(0) returns true; that value comes back unchanged through all eight frames, so is_odd(7) is true.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_parity exo_parity.c -lm && ./exo_parity
is_odd(7) is_even(6) is_odd(5) is_even(4) is_odd(3) is_even(2) is_odd(1) is_even(0) 
result 1
Output 3.18. Eight calls.

is_odd(-1) never meets 0: the argument decreases without end, and the program ends with a stack overflow (or, if the compiler turned the calls into jumps, runs until n−1n - 1 overflows, an undefined behaviour).

Exercise 3.10 ★★★

The naive Fibonacci function returns nn for n<2n < 2 and fib(n-1) + fib(n-2) otherwise, with F(0)=0F(0) = 0, F(1)=1F(1) = 1. Prove that fib(n), for n≥1n \geq 1, makes C(n)=2F(n+1)−1C(n) = 2F(n+1) - 1 calls, and that at most nn of them are on the stack at once. Compare the two for n=30n = 30 (F(31)=1 346 269F(31) = 1\,346\,269).

Solution

Solution of Exercise 3.10.

Calls: C(0)=C(1)=1C(0) = C(1) = 1, which equals 2F(1)−12F(1) - 1 and 2F(2)−12F(2) - 1. For n≥2n \geq 2, C(n)=1+C(n−1)+C(n−2)=1+2F(n)−1+2F(n−1)−1=2F(n+1)−1C(n) = 1 + C(n-1) + C(n-2) = 1 + 2F(n) - 1 + 2F(n-1) - 1 = 2F(n+1) - 1, by strong induction. Depth: the frames on the stack at one time are a path from the root of the tree of activations; along it the argument drops by at least 1 at each level, starts at nn, and a call with argument below 2 makes no call. A path therefore has at most nn nodes (n,n−1,…,1n, n-1, \dots, 1), and the path that always takes the left child has exactly nn. For n=30n = 30: 2 692 5372\,692\,537 calls, never more than 30 frames. The test tests/test_fib_calls.py checks both for n≤21n \leq 21.

Exercise 3.11 ★★★

Write a recursive function that solves the towers of Hanoi for nn discs, records each move (A->C), returns the number of moves and the greatest depth of recursion reached. Prove that it makes 2n−12^n - 1 moves and reaches depth n+1n + 1 when the first call has depth 1 and the calls with no disc count.

Solution

Solution of Exercise 3.11.

long hanoi(int n, char from, char to, char via, char *out, int depth, int *max_depth)
{
    if (depth > *max_depth)
        *max_depth = depth;
    if (n == 0)
        return 0;
    long moves = hanoi(n - 1, from, via, to, out, depth + 1, max_depth);
    if (out) {
        char move[6] = {from, '-', '>', to, ' ', '\0'};
        strcat(out, move);
    }
    moves += 1 + hanoi(n - 1, via, to, from, out, depth + 1, max_depth);
    return moves;
}
Hanoi, counting moves and depth code/bachelor-1/03-c-functions-and-stack/exercises/hanoi.c

Moves: M(0)=0M(0) = 0 and M(n)=2M(n−1)+1M(n) = 2M(n-1) + 1, so M(n)+1=2(M(n−1)+1)M(n) + 1 = 2(M(n-1) + 1) and M(n)=2n−1M(n) = 2^n - 1. Depth: a call with nn discs at depth tt makes calls with n−1n - 1 discs at depth t+1t + 1, down to the calls with 0 discs, at depth n+1n + 1; all calls at a given depth have the same number of discs, so no call goes deeper. The test tests/hanoi_test.c checks the move list for n=2n = 2 and both formulas for n≤20n \leq 20.

Exercise 3.12 ★★★

A recursive function has frames of ss bytes, and the stack holds SS bytes, of which cc are used before the first call. Give the greatest depth dd that fits, and prove it. Using the measurements of Output 3.7, find cc, and predict the last depth reached under a limit of 4096 KiB.

Solution

Solution of Exercise 3.12.

The frames of depths 0,…,d0, \dots, d fit exactly when c+(d+1)s≤Sc + (d + 1)s \leq S, so d=⌊(S−c)/s⌋−1d = \lfloor (S - c)/s \rfloor - 1. The four measurements constrain cc: for S=512S = 512 KiB, depth 500 is reached and 501 is not, so 501≤(524 288−c)/1040<502501 \leq (524\,288 - c)/1040 < 502, that is 2208<c≤32482208 < c \leq 3248. The other limits give 2144<c≤31842144 < c \leq 3184 (256 KiB, depth 248), 2336<c≤33762336 < c \leq 3376 (1024 KiB, depth 1004) and 1552<c≤25921552 < c \leq 2592 (2048 KiB, depth 2013); together, 2336<c≤25922336 < c \leq 2592, about 2.5 KiB. Under 4096 KiB: (4 194 304−c)/1040(4\,194\,304 - c)/1040 lies between 4030.54030.5 and 4030.74030.7, so d=4029d = 4029. A run with another environment shifts cc by its size, and the depth by a level or so.

3.6 Problem: How deep can a program go?

Problem 3.1

Weekend problem — How deep can a program go?

A recursive program uses two resources: time, counted in calls, and memory, counted in frames on the stack at once. The problem measures both for several shapes of recursion and turns the stack limit into a predicted depth. It uses the outputs of Listings 3.2 and 3.7, and the two programs below.

{
    enter(depth);
    return n == 0 ? 0 : 1 + count_down(n - 1, depth + 1);
}

long fib(int n, int depth)                        // binary: two calls inside
{
    enter(depth);
    return n < 2 ? n : fib(n - 1, depth + 1) + fib(n - 2, depth + 1);
}

long hanoi(int n, int depth)                      // binary, both of size n - 1
{
    enter(depth);
    return n == 0 ? 0 : hanoi(n - 1, depth + 1) + 1 + hanoi(n - 1, depth + 1);
}
Listing 3.19. Three shapes, instrumented by a call to enter(depth) (the rest of the file prints the table) code/bachelor-1/03-c-functions-and-stack/listings/shapes.c
$ gcc -std=c17 -O2 -Wall -Wextra -o shapes shapes.c -lm && ./shapes
shape        n    calls  depth
count_down   5        6      6
count_down  10       11     11
count_down  15       16     16
count_down  20       21     21
fib          5       15      5
fib         10      177     10
fib         15     1973     15
fib         20    21891     20
hanoi        5       63      6
hanoi       10     2047     11
hanoi       15    65535     16
hanoi       20  2097151     21
Output 3.13. Calls and greatest depth for n=5,10,15,20n = 5, 10, 15, 20.
bool is_even(long n)
{
    return n == 0 ? true : is_odd(n - 1);
}

bool is_odd(long n)
{
    return n == 0 ? false : is_even(n - 1);
}

int main(void)
{
    printf("is_even(10000000) = %d\n", is_even(10000000));
    return 0;
Listing 3.20. Mutual recursion ten million deep code/bachelor-1/03-c-functions-and-stack/listings/parity_deep.c
$ gcc -std=c17 -O0 parity_deep.c -o parity_O0
$ { ./parity_O0; } 2>/dev/null; echo "exit status $?"
exit status 139
$ gcc -std=c17 -O2 parity_deep.c -o parity_O2
$ ./parity_O2
is_even(10000000) = 1
$ gcc -std=c17 -O2 -S parity_deep.c -o - | grep -E '(call|jmp)\s+is_' | tr '\t' ' '
 jmp is_even
 call is_even
Output 3.14. The same program at -O0 and -O2, and the calls left in the -O2 assembly.

Part I — Frames measured.

  1. In Output 3.2, what is the size of one frame of descend? Why do we print differences of addresses rather than addresses?
  2. List what a frame of descend must contain at -O0, with sizes, and check that it can fit in that size with the alignment rule (the stack pointer plus 8 is a multiple of 16 at each function’s entry).
  3. In Output 3.7, the frame of dive measures 1040 bytes. Why more than 1000? Why is 1040 a multiple of 16?
  4. The program measures the frame size at depth 1, as the distance from depth 0. Why would it be wrong to measure it as the distance from a local of main?
  5. Why may the same programs give smaller frames at -O2? Which part of a frame can never disappear for a call that is not a tail call?
  6. Why must deep.c call fflush at each level, and why is its output sent to a file?

Part II — Calls against depth.

  1. Prove that count_down(n, 1) makes n+1n + 1 calls and reaches depth n+1n + 1; check the table.
  2. Prove by induction that hanoi(n, 1) makes 2n+1−12^{n+1} - 1 calls and reaches depth n+1n + 1; check the table.
  3. For fib, the table gives 15 calls for n=5n = 5. Check it against 2F(n+1)−12F(n+1) - 1, with F(6)=8F(6) = 8.
  4. Why does fib(n, 1) reach depth nn, not n+1n + 1?
  5. Between n=15n = 15 and n=20n = 20, by what factor did the calls of fib grow? Compare with φ5\varphi^5, where φ=(1+5)/2\varphi = (1 + \sqrt 5)/2.
  6. For each shape, give the ratio of calls to depth at n=20n = 20.
  7. The tree of activations of hanoi(n, 1) is a complete binary tree. Which nodes are its leaves, and how many are there?

Part III — Mutual recursion and tail calls.

  1. How many calls does is_even(10000000) make, and what is the greatest number of frames on the stack at -O0? Why did the -O0 program stop with status 139?
  2. In the -O2 assembly, is_odd ends with jmp is_even instead of call is_even. What does that change on the stack?
  3. The only call left is main’s. Why can the compiler not replace it by a jump?
  4. Is the call fib(n - 1, depth + 1) in fib a tail call? And the call count_down(n - 1, depth + 1) in 1 + count_down(...)?
  5. Rewrite count_down with an accumulator so that its recursive call is a tail call.

Part IV — The stack budget.

  1. With S=512S = 512 KiB and s=1040s = 1040 bytes, compute ⌊S/s⌋\lfloor S / s \rfloor and compare with the last depth reached, 500.
  2. Do the same for the three other limits of Output 3.7. Is the difference always the same? Explain why a constant cost counted in bytes, not in levels, accounts for all four.
  3. What does that cost consist of? Estimate in bytes the stack used before dive(0) starts.
  4. Under the default limit, 8192 KiB, predict the last depth reached by deep.c.
  5. Under the default limit and at -O0, how deep can descend of Listing 3.2 go, roughly?
  6. The evaluator nests one call of expr, term and factor per pair of parentheses. If its three frames take 48 bytes each, how many nested parentheses can a text have under 8192 KiB? What should a program that evaluates untrusted text do about it?
  7. State the named result of the problem, the depth bound, with the values measured here.
Solution

Solution of Problem 3.1.

1. 64 bytes. The addresses change from run to run (the system places the stack at a random place unless told otherwise), and they depend on the machine; the differences depend only on the frames.

2. The return address (8 bytes) and the saved frame pointer (8), then 48 bytes: the parameter (4) and local (4), here (8), an 8-byte guard value, and 24 bytes of padding. At the entry, rsp+8rsp + 8 is a multiple of 16; after the push of the frame pointer, rsprsp is a multiple of 16, and subtracting 48 keeps it so. Then the call inside pushes 8 bytes, and the rule holds for the next frame. 8+8+48=648 + 8 + 48 = 64.

3. Besides the array, the frame holds the return address, the saved frame pointer, the parameter depth and the guard value: 1000+8+8=10161000 + 8 + 8 = 1016 bytes below the frame pointer, rounded up to 1024 to keep the alignment, plus 16: 1040. Every frame is a multiple of 16 bytes, since the alignment rule holds at each entry.

4. main’s frame has another size; the distance from a local of main to the array of dive(0) mixes the two. Between two calls of dive, the distance is exactly one frame of dive.

5. At -O2, parameters and locals stay in registers, the frame pointer is not saved, and the guard is only kept where it is needed. The return address cannot disappear: a call that is not a jump must push it.

6. When standard output is a file or a pipe, printf fills a buffer and writes it when it is full or at a normal exit. The crash is not a normal exit: without fflush, the last lines would be lost. In a file, tail -n 1 shows only the last depth, out of hundreds of lines.

7. count_down(n, t) makes one call with n−1n - 1 at depth t+1t + 1 unless n=0n = 0. By induction the calls are count_down(n, 1), …, count_down(0, n+1): n+1n + 1 calls, depth n+1n + 1. Table: 21 and 21 for n=20n = 20.

8. Let K(n)K(n) be the calls: K(0)=1K(0) = 1 and K(n)=1+2K(n−1)K(n) = 1 + 2K(n-1), so K(n)+1=2(K(n−1)+1)K(n) + 1 = 2(K(n-1) + 1) and K(n)=2n+1−1K(n) = 2^{n+1} - 1. Depth: D(0)=1D(0) = 1, D(n)=1+D(n−1)D(n) = 1 + D(n-1), so D(n)=n+1D(n) = n + 1. Table: 221−1=2 097 1512^{21} - 1 = 2\,097\,151 and 21.

9. 2×8−1=152 \times 8 - 1 = 15.

10. The calls with argument 1 are leaves at depth nn (root at depth 1), and the call with argument 0 at the same level as 1 is never deeper; the deepest path is n,n−1,…,1n, n-1, \dots, 1: nn nodes.

11. 21 891/1973≈11.1021\,891 / 1973 \approx 11.10, and φ5≈11.09\varphi^5 \approx 11.09: F(n)F(n) grows like φn\varphi^n, and so do the calls.

12. count_down: 21/21=121/21 = 1. fib: 21 891/20≈109521\,891/20 \approx 1095. hanoi: 2 097 151/21≈99 8642\,097\,151/21 \approx 99\,864. Memory follows the depth, time follows the calls.

13. The leaves are the calls with n=0n = 0, all at depth n+1n + 1: 2n2^n of them, for 2n+1−12^{n+1} - 1 nodes.

14. 10 000 00110\,000\,001 calls, and all of them on the stack at once at -O0, plus main. Each frame holds at least a return address and a saved frame pointer (16 bytes; 32 at -O0 here), that is over 160 MB, far beyond the 8 MiB stack: a stack overflow, and the system stops the program.

15. A jump does not push a return address and is_odd, at -O2, has no frame: the return address on top of the stack stays main’s, and when is_even finally executes ret, control goes straight back to main. The stack does not grow with nn.

16. main still has work after the call: it passes the result to printf. It needs its return address.

17. Neither: fib adds the two results after the calls return, and count_down adds 1 after its call returns.

18. Pass the count so far as a second parameter, the accumulator: long count_acc(int n, long acc) returns acc when n == 0, and otherwise returns count_acc(n - 1, acc + 1); the first call is count_acc(n, 0).

19. ⌊524 288/1040⌋=504\lfloor 524\,288 / 1040 \rfloor = 504; 504−500=4504 - 500 = 4.

20. ⌊262 144/1040⌋=252\lfloor 262\,144/1040 \rfloor = 252, 252−248=4252 - 248 = 4; ⌊1 048 576/1040⌋=1008\lfloor 1\,048\,576/1040 \rfloor = 1008, 1008−1004=41008 - 1004 = 4; ⌊2 097 152/1040⌋=2016\lfloor 2\,097\,152/1040 \rfloor = 2016, 2016−2013=32016 - 2013 = 3. Not always the same: the cost is a fixed number of bytes cc, and d=⌊(S−c)/s⌋−1d = \lfloor (S - c)/s \rfloor - 1 (Exercise 3.12). How many levels cc removes depends on the fractional part of S/sS/s, which is 0.060.06, 0.120.12, 0.250.25 and 0.490.49 for the four limits: with the largest, cc costs one level fewer.

21. The stack holds more than the frames of dive: the program’s arguments and environment strings (almost none here, the environment being empty), the information the system passes at start-up, the frames of the start-up code and of main, and, at the deepest level, the frames of printf. The four measurements give 2336<c≤25922336 < c \leq 2592 bytes (Exercise 3.12): about 2.5 KiB.

22. (8 388 608−c)/1040(8\,388\,608 - c)/1040 with 2336<c≤25922336 < c \leq 2592 lies between 8063.48063.4 and 8063.88063.8: d=8062d = 8062.

23. About 8 388 608/64≈131 0008\,388\,608/64 \approx 131\,000 levels, a little less for the start-up cost.

24. Each pair costs 3×48=1443 \times 48 = 144 bytes: 8 388 608/144≈58 0008\,388\,608 / 144 \approx 58\,000 nested parentheses. A text of 60 000 opening parentheses would crash the evaluator: a program that reads untrusted text must limit the nesting depth it accepts (and report an error beyond it), or use an explicit stack in a loop.

25. The depth bound. A recursion with frames of ss bytes, under a stack limit of SS bytes, reaches at most dmax⁡=⌊S/s⌋d_{\max} = \lfloor S/s \rfloor levels; precisely d=⌊(S−c)/s⌋−1d = \lfloor (S - c)/s \rfloor - 1, where cc is the stack used before the first call. Here, with s=1040s = 1040 bytes, the last depths reached for limits of 256 to 2048 KiB were 248, 500, 1004 and 2013, 3 or 4 below ⌊S/s⌋\lfloor S/s \rfloor, all explained by one start-up cost cc between 2337 and 2592 bytes. Calls cost time and depth costs stack: binary recursion makes exponentially many calls with linear depth, and a tail call compiled as a jump costs no depth at all.

本章定义的术语

在术语表中查看全部 1050 个术语