Computer Science · Book 3 · Bachelor Year 1

University Computer Science — Year 1

University Computer Science — Year 1 · Bachelor Year 1

5Dynamic Memory

A program must read the rainfall readings of a file, and the file may hold forty numbers or forty million. The arrays of Chapter 4 have a size fixed in the source; a local array lives in a frame of a stack limited to 8 MiB; and both vanish when their function or the program ends. What the program needs is memory asked for while it runs, in the amount the data require, kept for exactly as long as it is useful. C provides it, and hands the programmer the duty to give it back. This chapter is about both halves of that bargain.

You already know

A running program’s memory has regions: code, initialised and zero-initialised data, the call stack, and the heap (Chapter 1). A pointer holds an address and a type; void * holds an address of anything; and sizeof gives sizes in bytes (Chapter 4).

5.1 malloc and free

Definition 5.1 (Heap, dynamic allocation)

The heap is the region of a running program’s memory from which blocks are handed out on request while it runs. Dynamic allocation is the obtaining of such a block: malloc(n) returns the address of a new block of n bytes, or the null pointer if it cannot. The block exists until the program passes its address to free, whatever functions return in between.

#include <stdlib.h>

int main(int argc, char **argv)
{
    size_t n = argc > 1 ? (size_t)atoi(argv[1]) : 10;
    int *squares = malloc(n * sizeof *squares);      // room for n ints, on the heap
    if (squares == NULL) {
        printf("out of memory\n");
        return 1;
    }
    for (size_t i = 0; i < n; i++)
        squares[i] = (int)(i * i);
    long sum = 0;
    for (size_t i = 0; i < n; i++)
        sum += squares[i];
    printf("%zu squares, sum %ld, last %d\n", n, sum, squares[n - 1]);
    free(squares);                                   // give the block back
    int *zeros = calloc(n, sizeof *zeros);           // calloc: the block starts at zero
    if (zeros == NULL)
        return 1;
    printf("calloc gave %d %d %d ...\n", zeros[0], zeros[1], zeros[2]);
    free(zeros);
    return 0;
}
Listing 5.1. An array whose length comes from the command line code/bachelor-1/05-dynamic-memory/listings/alloc_basic.c
$ gcc -std=c17 -O2 -Wall -Wextra -o alloc_basic alloc_basic.c -lm && ./alloc_basic 1000
1000 squares, sum 332833500, last 998001
calloc gave 0 0 0 ...
Output 5.1. Run with the argument 1000.

Four habits are visible in these lines. The size is written n * sizeof *squares: the size of what the pointer points to, which stays right if the type of squares changes. The result of malloc, a void *, is stored without a cast, since C converts it. The result is tested against NULL before use. And every malloc has its free. calloc(n, size) allocates n elements and fills them with zero bytes; malloc leaves the block’s contents indeterminate.

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

int main(void)
{
    size_t huge = SIZE_MAX / 2;                      // about 9.2e18 bytes
    char *p = malloc(huge);
    if (p == NULL)
        printf("malloc(%zu) returned NULL\n", huge);
    else
        free(p);
    return 0;
}
Listing 5.2. Asking for too much code/bachelor-1/05-dynamic-memory/listings/nullcheck.c
$ gcc -std=c17 -O2 -Wall -Wextra -o nullcheck nullcheck.c -lm && ./nullcheck
malloc(9223372036854775807) returned NULL
Output 5.2. malloc cannot find nine exabytes and says so.

To change the size of a block, realloc(p, n) returns a block of n bytes holding the old contents (as much as fits): the same block if it can grow in place, otherwise a new one, the old one being freed. If it fails it returns NULL and leaves the old block untouched. So its result goes into a new variable: writing a = realloc(a, ...) would lose the only address of the old block on failure (Exercise 5.5).

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t cap = 4;
    int *a = malloc(cap * sizeof *a);
    if (a == NULL)
        return 1;
    for (size_t i = 0; i < cap; i++)
        a[i] = (int)(10 * i);
    int *bigger = realloc(a, 2 * cap * sizeof *a);   // a new variable: a survives a failure
    if (bigger == NULL) {
        free(a);
        return 1;
    }
    a = bigger;                                      // the old a may be invalid now: forget it
    for (size_t i = cap; i < 2 * cap; i++)
        a[i] = (int)(10 * i);
    cap *= 2;
    for (size_t i = 0; i < cap; i++)
        printf("%d ", a[i]);
    printf("\n");
    free(a);
    return 0;
}
Listing 5.3. Growing a block safely code/bachelor-1/05-dynamic-memory/listings/realloc_grow.c
$ gcc -std=c17 -O2 -Wall -Wextra -o realloc_grow realloc_grow.c -lm && ./realloc_grow
0 10 20 30 40 50 60 70 
Output 5.3. The first four values survived the move.
Near the end of . The pointers live in main’s frame; the blocks they hold the addresses of live on the heap. The first block has been freed: squares still holds its address, but the block is no longer the program’s.
Near the end of Listing 5.1. The pointers live in main’s frame; the blocks they hold the addresses of live on the heap. The first block has been freed: squares still holds its address, but the block is no longer the program’s.
Two lifetimes. A local of f ends when f returns; a block that f obtains from malloc lasts until some part of the program frees it, possibly far from f. The programmer, not the call structure, chooses when.
Two lifetimes. A local of f ends when f returns; a block that f obtains from malloc lasts until some part of the program frees it, possibly far from f. The programmer, not the call structure, chooses when.

Compare with Chapter 3: a function could not return the address of a local, which died with its frame; it can return the address of a block it allocated, which lives on. In exchange, the program must know at every moment which blocks it still needs, and free the others exactly once.

5.2 Errors and the tools that find them

Manual memory management fails in four classic ways. None is detected by the language; each is detected, when a run performs it, by the address sanitizer of Chapter 4.

Definition 5.2 (Memory leak)

A memory leak is a heap block that the program no longer frees because it no longer holds its address anywhere, or no longer needs it but keeps it. A leaking program’s memory grows with the time it runs.

#include <stdio.h>
#include <stdlib.h>

char *make_label(int n)
{
    char *label = malloc(16);
    if (label != NULL)
        snprintf(label, 16, "item %d", n);
    return label;                                    // the caller must free it
}

int main(void)
{
    char *s = NULL;
    for (int i = 1; i <= 3; i++) {
        s = make_label(i);                           // the previous block's only address is lost
        printf("%s\n", s);
    }
    free(s);                                         // frees the last block only
    fflush(stdout);                                  // print now: the leak report ends the run
    return 0;
}
Listing 5.4. A pointer overwritten before its block was freed code/bachelor-1/05-dynamic-memory/listings/leak.c
$ gcc -std=c17 -O1 -g -fsanitize=address leak.c -o leak
$ ./leak
item 1
item 2
item 3

=================================================================
==1000==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 32 byte(s) in 2 object(s) allocated from:
    #0 0x7ffff74b4887 in __interceptor_malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:145
    #1 0x55555555527e in make_label ~/session/leak.c:7
Output 5.4. At the end of the run, the leak detector lists the blocks still allocated that nothing points to. Some lines are left out.

The address sanitizer includes a leak detector, LeakSanitizer, which runs when the program ends. It scans the memory the program can still reach (globals, the stack, registers, the blocks reachable from them) for values that look like addresses of heap blocks; a block that nothing points to is reported. The two blocks of item 1 and item 2 were lost when s was overwritten. The scan is conservative: a stale copy of an address left in a dead stack slot makes its block look reachable, which is why this session builds at -O1, where no such copy survives. The detector may miss a leak; it does not invent one.

Definition 5.3 (Dangling pointer, use after free, double free)

After free(p), every pointer that held the block’s address is a dangling pointer: it still holds the number, but the block is no longer the program’s. Reading or writing through it is a use after free; passing it to free again is a double free. Both are undefined behaviour.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int *scores = malloc(4 * sizeof *scores);
    if (scores == NULL)
        return 1;
    scores[0] = 17;
    free(scores);
    printf("first score: %d\n", scores[0]);         // scores is now a dangling pointer
    return 0;
}
Listing 5.5. A read after free code/bachelor-1/05-dynamic-memory/listings/uaf.c
$ gcc -std=c17 -O0 -g -fsanitize=address uaf.c -o uaf
$ ./uaf
=================================================================
==1000==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000010 at pc 0x5555555552f8 bp 0x7fffffffeca0 sp 0x7fffffffec90
READ of size 4 at 0x502000000010 thread T0
    #0 0x5555555552f7 in main ~/session/uaf.c:12
0x502000000010 is located 0 bytes inside of 16-byte region [0x502000000010,0x502000000020)
freed by thread T0 here:
    #0 0x7ffff74b4537 in __interceptor_free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:127
    #1 0x5555555552c0 in main ~/session/uaf.c:11
previously allocated by thread T0 here:
    #0 0x7ffff74b4887 in __interceptor_malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:145
    #1 0x55555555525e in main ~/session/uaf.c:7
Output 5.5. The report gives three stacks: the bad read, the free, and the malloc. Some lines are left out.

A use-after-free report tells the whole story of the block: where it was allocated (line 7), where it was freed (line 11), and where it was used afterwards (line 12). Without the sanitizer, this program would most likely print 17, since nobody has reused the block yet; the next malloc could reuse it, and then the read would return someone else’s data.

#include <stdlib.h>

int main(void)
{
    int *a = malloc(8 * sizeof *a);
    int *b = a;                                      // b and a point to the same block
    free(a);
    free(b);                                         // the same block, freed again
    return 0;
}
Listing 5.6. Two pointers, one block, two free code/bachelor-1/05-dynamic-memory/listings/double_free.c
$ gcc -std=c17 -O0 -g -fsanitize=address double_free.c -o double_free
$ ./double_free
=================================================================
==1000==ERROR: AddressSanitizer: attempting double-free on 0x503000000040 in thread T0:
    #0 0x7ffff74b4537 in __interceptor_free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:127
    #1 0x5555555551e2 in main ~/session/double_free.c:9
freed by thread T0 here:
    #0 0x7ffff74b4537 in __interceptor_free ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:127
    #1 0x5555555551d6 in main ~/session/double_free.c:8
Output 5.6. The second free is reported, with the first. Some lines are left out.
Freeing a block through one pointer leaves every other copy of its address dangling. Nothing in the pointers changes; only the block’s status does, which is why the error is invisible in the source.
Freeing a block through one pointer leaves every other copy of its address dangling. Nothing in the pointers changes; only the block’s status does, which is why the error is invisible in the source.

The fourth error, reading memory that was never given a value, is not an address error and the address sanitizer does not see it. For a local variable the compiler often does.

#include <stdio.h>

int main(void)
{
    int marks[4] = {12, 15, 9, 14};
    int total;
    for (int i = 0; i < 4; i++)
        total += marks[i];
    printf("total %d\n", total);
    return 0;
}
Listing 5.7. A total never set to zero code/bachelor-1/05-dynamic-memory/listings/uninit.c
$ gcc -std=c17 -O2 -Wall -Wextra -c uninit.c
uninit.c: In function 'main':
uninit.c:9:15: warning: 'total' is used uninitialized [-Wuninitialized]
    9 |         total += marks[i];
      |         ~~~~~~^~~~~~~~~~~
Output 5.7. The warning of -Wall at -O2.

For a block from malloc, whose contents are indeterminate, no warning comes: the block may be filled by a loop the compiler cannot follow. Use calloc, or write every element before reading it. A debugger, the tool that stops a running program and shows its variables, is the subject of a section of Chapter 7.

5.3 Who frees what

Every block must be freed once, by someone, after its last use. In a program of a few hundred lines with blocks passed between functions, this works only with a convention, written where every caller reads it: in the comment of the interface. The C library itself follows one: a block from malloc is the caller’s to free; a pointer returned by getenv must never be freed.

Method 5.4 (Writing down who frees)

For each function that receives or returns a pointer to a heap block, state in its interface comment:

  1. whether a returned block belongs to the caller, who must free it (as for malloc);
  2. whether a pointer it receives is kept (the function takes charge of the block) or only borrowed during the call;
  3. for a returned pointer into a block that the callee keeps (a borrowed pointer), until when it stays valid.

Then give every structure a pair of functions, one that creates and one that destroys, and free in the destroying function everything the structure holds.

The phone book of the weekend problem states its convention in its header; here it is, with the structure it describes. A struct groups several variables under one name, accessed with . or, through a pointer, ->; Chapter 6 treats structures in full.

// Convention: the book owns the names it stores. book_add copies the name it is given;
// book_remove and book_destroy free the names they drop. A pointer returned by book_find
// is borrowed: the caller must not free it, and it is valid only until the next
// book_add or book_remove.
#ifndef PHONEBOOK_H
#define PHONEBOOK_H
#include <stddef.h>

struct contact {
    char *name;
    long number;
};

struct book {
    struct contact *items;      // a heap block of cap contacts, len of them used
    size_t len, cap;
    int policy;                 // > 0: add `policy` slots; -4: double; -3: multiply by 1.5
    long copies;                // contacts copied by the growths
};

void book_init(struct book *b, int policy);
int book_add(struct book *b, const char *name, long number);
const struct contact *book_find(const struct book *b, const char *name);
int book_remove(struct book *b, const char *name);
void book_destroy(struct book *b);

#endif
Listing 5.8. An interface that says who frees code/bachelor-1/05-dynamic-memory/listings/phonebook.h

The pointer returned by book_find is borrowed, and the comment says until when: an addition may move the whole array of contacts to a bigger block, and a removal frees a name. The Year 2 volume shows a language in which this kind of convention is checked by the compiler; in C it is checked by people and by sanitizers.

5.4 A growable array written by hand

To read an unknown number of values, keep them in a heap block with room to spare, and move them to a bigger block when it is full. The structure holds the block’s address, the number of elements used, and the capacity of the block.


void intvec_init(struct intvec *v)
{
    v->data = NULL;
    v->len = v->cap = 0;
    v->copies = 0;
}

int intvec_push(struct intvec *v, int x)
{
    if (v->len == v->cap) {                         // full: move to a block twice as big
        size_t cap = v->cap == 0 ? 1 : 2 * v->cap;
        int *bigger = malloc(cap * sizeof *bigger);
        if (bigger == NULL)
            return -1;                              // v is unchanged
        for (size_t i = 0; i < v->len; i++)
            bigger[i] = v->data[i];                 // the copies that growth costs
        v->copies += (long)v->len;
        free(v->data);
        v->data = bigger;
        v->cap = cap;
    }
    v->data[v->len++] = x;
    return 0;
}

void intvec_free(struct intvec *v)
{
    free(v->data);
    intvec_init(v);
}
Listing 5.9. Pushing onto a growable array of int code/bachelor-1/05-dynamic-memory/listings/intvec.c
$ gcc -std=c17 -O2 -Wall -Wextra -o read_all read_all.c intvec.c -lm && ./read_all
capacity 0 -> 1 when number 1 arrives
capacity 1 -> 2 when number 2 arrives
capacity 2 -> 4 when number 3 arrives
capacity 4 -> 8 when number 5 arrives
capacity 8 -> 16 when number 9 arrives
capacity 16 -> 32 when number 17 arrives
capacity 32 -> 64 when number 33 arrives
40 numbers, sum 752, 63 element copies
Output 5.8. Forty daily rainfalls of the town, in tenths of a millimetre, read from standard input.

Definition 5.5 (Growth factor)

A growable array whose capacity, when full, is multiplied by a fixed r>1r > 1 has growth factor rr. The alternative is to add a fixed number kk of slots at each growth.

Growth costs copies: moving from a full block of capacity cc copies cc elements. With growth by one slot, reaching nn elements copies 1+2+⋯+(n−1)=n(n−1)/21 + 2 + \dots + (n-1) = n(n-1)/2 elements; with doubling, it copies 1+2+4+…1 + 2 + 4 + \dots up to the last power of two below nn, fewer than 2n2n. The program below counts both without allocating anything.

#include <stdio.h>

long copies_plus_one(long n)        // capacity 1, 2, 3, ...: copy everything each time
{
    long copies = 0;
    for (long cap = 1; cap < n; cap++)
        copies += cap;              // growing from cap to cap + 1 copies cap elements
    return copies;
}

long copies_doubling(long n)        // capacity 1, 2, 4, 8, ...
{
    long copies = 0;
    for (long cap = 1; cap < n; cap *= 2)
        copies += cap;
    return copies;
}

int main(void)
{
    printf("%9s %15s %12s %7s\n", "n", "+1 copies", "x2 copies", "x2 / n");
    for (long n = 1000; n <= 1000000; n *= 10)
        printf("%9ld %15ld %12ld %7.3f\n", n, copies_plus_one(n), copies_doubling(n),
               (double)copies_doubling(n) / (double)n);
    return 0;
}
Listing 5.10. Counting the copies of two growth rules code/bachelor-1/05-dynamic-memory/listings/copies.c
$ gcc -std=c17 -O2 -Wall -Wextra -o copies copies.c -lm && ./copies
        n       +1 copies    x2 copies  x2 / n
     1000          499500         1023   1.023
    10000        49995000        16383   1.638
   100000      4999950000       131071   1.311
  1000000    499999500000      1048575   1.049
Output 5.9. Half a trillion copies against a million, for a million elements.

Proposition 5.6 (Doubling copies fewer than 2n2n elements)

A growable array that starts with capacity 1 and doubles its capacity when full copies fewer than 2n2n elements in all while n≥1n \geq 1 elements are pushed.

Proof. The growths happen at capacities 1,2,4,…,2m1, 2, 4, \dots, 2^m, where 2m2^m is the largest power of two below nn (a growth happens when the array is full and one more element arrives, so its capacity is less than nn). They copy 1+2+⋯+2m=2m+1−11 + 2 + \dots + 2^m = 2^{m+1} - 1 elements, and 2m<n2^m < n gives 2m+1−1<2n2^{m+1} - 1 < 2n. If n=1n = 1, there is no growth and no copy. ∎

So each push costs, on average over the whole sequence, fewer than two copies, however large nn is; doubling also wastes at most half the block. Chapter 14 turns this observation into a method, amortised analysis, and calls the structure by its usual name.

Doubling from capacity 1 to 16. Each new block receives a copy of the full block before it, half its size: 1 + 2 + 4 + 8 = 15 copies to reach 16 elements, fewer than 2 × 16.
Doubling from capacity 1 to 16. Each new block receives a copy of the full block before it, half its size: 1+2+4+8=151 + 2 + 4 + 8 = 15 copies to reach 16 elements, fewer than 2×162 \times 16.

5.5 Two-dimensional arrays of unknown size

A grid of h×wh \times w numbers known only at run time can be stored in two ways. The first allocates a table of hh row pointers, then one block per row: g[i][j] works as for a static array, but there are h+1h + 1 blocks to allocate, check and free.

double **grid_new(size_t h, size_t w)
{
    double **rows = malloc(h * sizeof *rows);          // h pointers
    if (rows == NULL)
        return NULL;
    for (size_t i = 0; i < h; i++) {
        rows[i] = calloc(w, sizeof *rows[i]);           // one block per row
        if (rows[i] == NULL) {
            while (i > 0)
                free(rows[--i]);                        // undo what was done
            free(rows);
            return NULL;
        }
    }
    return rows;
}

void grid_free(double **rows, size_t h)
{
    for (size_t i = 0; i < h; i++)
        free(rows[i]);                                  // the rows first,
    free(rows);                                         // then the table of rows
}

int main(void)
{
    size_t h = 3, w = 5;
    double **g = grid_new(h, w);
    if (g == NULL)
        return 1;
    g[2][4] = 1.5;                                      // two dereferences
    printf("g[2][4] = %.1f, %zu + 1 blocks\n", g[2][4], h);
    grid_free(g, h);
    return 0;
}
Listing 5.11. One block per row code/bachelor-1/05-dynamic-memory/listings/grid_rows.c
$ gcc -std=c17 -O2 -Wall -Wextra -o grid_rows grid_rows.c -lm && ./grid_rows
g[2][4] = 1.5, 3 + 1 blocks
Output 5.10. Four blocks for a 3×53 \times 5 grid.

Definition 5.7 (Linearised array)

A linearised array stores the elements of an h×wh \times w grid in a single block of h⋅wh \cdot w elements, in row-major order: element (i,j)(i, j) is at index i⋅w+ji \cdot w + j.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    size_t h = 3, w = 5;
    double *g = calloc(h * w, sizeof *g);               // one block of h * w doubles
    if (g == NULL)
        return 1;
    g[2 * w + 4] = 1.5;                                 // element (2, 4): index i * w + j
    printf("g[2 * w + 4] = %.1f, 1 block of %zu bytes\n", g[2 * w + 4], h * w * sizeof *g);
    free(g);
    return 0;
}
Listing 5.12. The same grid in one block code/bachelor-1/05-dynamic-memory/listings/grid_flat.c
$ gcc -std=c17 -O2 -Wall -Wextra -o grid_flat grid_flat.c -lm && ./grid_flat
g[2 * w + 4] = 1.5, 1 block of 120 bytes
Output 5.11. One allocation, one free.

The linearised form makes one allocation and one free, keeps all elements contiguous (which the caches of the processor reward, as the Year 2 volume measures), and lets the program pass the whole grid as one pointer. The table of rows allows rows of different lengths, and swapping two rows by exchanging two pointers. Images, matrices and the spreadsheet of Chapter 4 are nearly always linearised.

Safe use

Build and test every program that allocates with -fsanitize=address, which includes the leak detector. Free every block exactly once, set a pointer to NULL after freeing it when it outlives the free (freeing NULL does nothing), and never return or keep a pointer whose block someone else may free.

5.6 Exercises

Exercise 5.1 ★

Each function below contains one memory error. Name it, and say whether the address sanitizer would report it.

int a(void)
{
    int *p = malloc(10 * sizeof *p);
    p[10] = 1;
    free(p);
    return 0;
}

int b(int n)
{
    int *p = malloc(10 * sizeof *p);
    if (n > 100)
        return -1;
    free(p);
    return 0;
}

int c(void)
{
    char *s = malloc(6);
    strcpy(s, "hello");
    free(s);
    return s[0] == 'h';
}

int d(void)
{
    int x = 5;
    int *p = &x;
    free(p);
    return 0;
}
Listing 5.13. Four errors code/bachelor-1/05-dynamic-memory/listings/exo_which.c
Solution

Solution of Exercise 5.1.

a: p[10] writes one element past a block of 10, a heap buffer overflow; reported. b: when n > 100 the function returns without freeing p, a leak; reported by the leak detector at the end of a run that takes that path. c: s[0] is read after free(s), a use after free; reported. d: p points to a local variable, which did not come from malloc; freeing it is undefined behaviour, and the sanitizer reports an attempt to free memory that was not allocated by malloc.

Exercise 5.2 ★

How many bytes does malloc(n * sizeof *r) request for n=10n = 10 in the program below? Predict, then explain the size of struct reading, knowing that a double must start at a multiple of 8.

#include <stdio.h>

struct reading {
    double value;
    int station;
    char unit;
};

int main(void)
{
    size_t n = 10;
    struct reading *r;
    printf("sizeof *r = %zu, request = %zu bytes\n", sizeof *r, n * sizeof *r);
    return 0;
}
Listing 5.14. The size of a request code/bachelor-1/05-dynamic-memory/listings/exo_bytes.c
Solution

Solution of Exercise 5.2.

The members take 8+4+1=138 + 4 + 1 = 13 bytes; the structure is padded to 16 so that, in an array of structures, every value starts at a multiple of 8. Ten of them: 160 bytes. sizeof *r does not read r, which may therefore be uninitialised.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_bytes exo_bytes.c -lm && ./exo_bytes
sizeof *r = 16, request = 160 bytes
Output 5.15. The sizes.

Exercise 5.3 ★

Predict the four numbers printed, and say which variable may no longer be used after the realloc.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int *a = malloc(3 * sizeof *a);
    if (a == NULL)
        return 1;
    a[0] = 7; a[1] = 8; a[2] = 9;
    int *b = realloc(a, 1000 * sizeof *a);            // likely to move to a new block
    if (b == NULL) {
        free(a);
        return 1;
    }
    b[3] = b[0] + b[2];
    printf("%d %d %d %d\n", b[0], b[1], b[2], b[3]);
    free(b);
    return 0;
}
Listing 5.15. What survives a realloc code/bachelor-1/05-dynamic-memory/listings/exo_realloc.c
Solution

Solution of Exercise 5.3.

realloc keeps the first three values, wherever the block goes; b[3] =7+9=16= 7 + 9 = 16. If the block moved, a holds the address of a freed block: after a successful realloc, only b may be used.

$ gcc -std=c17 -O2 -Wall -Wextra -o exo_realloc exo_realloc.c -lm && ./exo_realloc
7 8 9 16
Output 5.16. The output.

Exercise 5.4 ★

One path through sum_file leaks. Which one? Fix it with one line.

int sum_file(const char *path, long *total)
{
    int *buffer = malloc(1000 * sizeof *buffer);
    if (buffer == NULL)
        return -1;
    FILE *f = fopen(path, "r");
    if (f == NULL)
        return -1;
    size_t n = 0;
    while (n < 1000 && fscanf(f, "%d", &buffer[n]) == 1)
        n++;
    fclose(f);
    *total = 0;
    for (size_t i = 0; i < n; i++)
        *total += buffer[i];
    free(buffer);
    return 0;
}
Listing 5.16. Find the leak code/bachelor-1/05-dynamic-memory/listings/exo_where_leak.c
Solution

Solution of Exercise 5.4.

When fopen fails, the function returns −1-1 and buffer is lost. Free it on that path: if (f == NULL) { free(buffer); return -1; }, or open the file before allocating.

Exercise 5.5 ★★

The function grow below is correct when memory is plentiful. What happens when realloc fails? Rewrite it.

#include <stdlib.h>

int grow(int **a, size_t *cap)
{
    *a = realloc(*a, 2 * *cap * sizeof **a);
    if (*a == NULL)
        return -1;
    *cap *= 2;
    return 0;
}
Listing 5.17. The tempting realloc code/bachelor-1/05-dynamic-memory/listings/exo_realloc_bad.c
Solution

Solution of Exercise 5.5.

If realloc fails it returns NULL, which grow stores into *a: the only address of the old block, still allocated and holding the caller’s data, is lost (a leak), and the caller’s array is gone. The result must go to a new variable: int *bigger = realloc(*a, 2 * *cap * sizeof **a); if (bigger == NULL) return -1; *a = bigger; *cap *= 2;. On failure the caller still has its array, unchanged.

Exercise 5.6 ★★

The loop at the end of the program frees a chain of three nodes. Read the report, explain the bug, and fix the loop.

struct node {
    int value;
    struct node *next;
};

int main(void)
{
    struct node *head = NULL;
    for (int v = 3; v >= 1; v--) {                     // builds 1 -> 2 -> 3
        struct node *n = malloc(sizeof *n);
        if (n == NULL)
            return 1;
        n->value = v;
        n->next = head;
        head = n;
    }
    for (struct node *p = head; p != NULL; p = p->next)
        free(p);
    printf("freed\n");
    return 0;
}
Listing 5.18. Freeing a chain code/bachelor-1/05-dynamic-memory/listings/exo_chain.c
$ gcc -std=c17 -O0 -g -fsanitize=address exo_chain.c -o exo_chain
$ ./exo_chain
=================================================================
==1000==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000058 at pc 0x555555555362 bp 0x7fffffffec80 sp 0x7fffffffec70
READ of size 8 at 0x502000000058 thread T0
    #0 0x555555555361 in main ~/session/exo_chain.c:21
Output 5.12. The first lines of the report. Some lines are left out.
Solution

Solution of Exercise 5.6.

The loop’s step p = p->next runs after free(p): it reads the field next of a freed node (8 bytes at offset 8 of a 16-byte block, which the report locates at line 21). Save the next node first: struct node *p = head; while (p != NULL) { struct node *next = p->next; free(p); p = next; }.

Exercise 5.7 ★★

Write char *my_strdup(const char *s), which returns a new heap block holding a copy of the string s (its characters and the final zero byte), or NULL. State its convention for freeing.

Solution

Solution of Exercise 5.7.

The returned block belongs to the caller, who must free it, and s is only read; the test is tests/strdup_test.c.

char *my_strdup(const char *s)
{
    size_t n = 0;
    while (s[n] != '\0')
        n++;
    char *copy = malloc(n + 1);                         // + 1: the final zero byte
    if (copy == NULL)
        return NULL;
    for (size_t i = 0; i <= n; i++)                     // <= n: copies the zero too
        copy[i] = s[i];
    return copy;
}
Count, allocate, copy code/bachelor-1/05-dynamic-memory/exercises/my_strdup.c

Exercise 5.8 ★★

Write int **grid2d_new(size_t h, size_t w), which allocates a zero-filled grid as a table of rows, and grid2d_free. If an allocation fails halfway, grid2d_new must return NULL without leaking.

Solution

Solution of Exercise 5.8.

int **grid2d_new(size_t h, size_t w)
{
    int **g = malloc(h * sizeof *g);
    if (g == NULL)
        return NULL;
    for (size_t i = 0; i < h; i++) {
        g[i] = calloc(w, sizeof *g[i]);
        if (g[i] == NULL) {
            grid2d_free(g, i);          // the i rows made so far
            return NULL;
        }
    }
    return g;
}

void grid2d_free(int **g, size_t h)
{
    if (g == NULL)
        return;
    for (size_t i = 0; i < h; i++)
        free(g[i]);
    free(g);
}
Rows, and a clean failure code/bachelor-1/05-dynamic-memory/exercises/grid2d.c

When row ii cannot be allocated, rows 0,…,i−10, \dots, i-1 and the table exist: grid2d_free(g, i) frees exactly those. The test is tests/grid_test.c.

Exercise 5.9 ★★

A growable array starts with capacity kk and adds kk slots when full. Show that pushing nn elements copies k m(m+1)/2k\,m(m+1)/2 elements, where m=⌊(n−1)/k⌋m = \lfloor (n-1)/k \rfloor, roughly n2/(2k)n^2/(2k). Check it against the +16 row of Output 5.14 for n=1000n = 1000.

Solution

Solution of Exercise 5.9.

A growth happens when the array is full at a capacity below nn: at capacities k,2k,…,mkk, 2k, \dots, mk with mk<nmk < n, that is m=⌊(n−1)/k⌋m = \lfloor (n-1)/k \rfloor. They copy k+2k+⋯+mk=k m(m+1)/2k + 2k + \dots + mk = k\,m(m+1)/2 elements, and m≈n/km \approx n/k gives about n2/(2k)n^2/(2k). For n=1000n = 1000 and k=16k = 16: m=62m = 62 and 16×62×63/2=31 24816 \times 62 \times 63/2 = 31\,248, as printed. The test tests/test_growth_counts.py checks the formula.

Exercise 5.10 ★★★

Prove Proposition 5.6 again for an array that starts at capacity c0≥1c_0 \geq 1, and show that the bound 2n2n cannot be replaced by (2−ε)n(2 - \varepsilon)n for any ε>0\varepsilon > 0.

Solution

Solution of Exercise 5.10.

The growths happen at capacities c0,2c0,…,2mc0c_0, 2c_0, \dots, 2^m c_0, all below nn, and copy c0(2m+1−1)<2⋅2mc0<2nc_0(2^{m+1} - 1) < 2 \cdot 2^m c_0 < 2n elements. For c0=1c_0 = 1 and n=2m+1n = 2^m + 1, the copies are 2m+1−1=2n−32^{m+1} - 1 = 2n - 3, and (2n−3)/n(2n - 3)/n tends to 2: no bound (2−ε)n(2 - \varepsilon)n holds for all nn.

Exercise 5.11 ★★★

A program allocates and frees many blocks of one size. Write a pool: one malloc of count blocks at the start, then pool_get and pool_put in constant time, keeping the free blocks in a chain that runs through their own first bytes. Why must each block be at least as large as a pointer?

Solution

Solution of Exercise 5.11.

int pool_init(struct pool *p, size_t size, size_t count)
{
    if (size < sizeof(void *))
        size = sizeof(void *);                              // room for the link
    size = (size + sizeof(void *) - 1) / sizeof(void *) * sizeof(void *);   // aligned
    p->memory = malloc(size * count);
    if (p->memory == NULL)
        return -1;
    p->size = size;
    p->count = count;
    p->in_use = 0;
    p->free_list = NULL;
    for (size_t i = count; i > 0; i--) {                    // chain them, block 0 first
        void *block = p->memory + (i - 1) * size;
        *(void **)block = p->free_list;
        p->free_list = block;
    }
    return 0;
}
void *pool_get(struct pool *p)
{
    void *block = p->free_list;
    if (block == NULL)
        return NULL;
    p->free_list = *(void **)block;                         // unlink the first free block
    p->in_use++;
    return block;
}

void pool_put(struct pool *p, void *block)
{
    *(void **)block = p->free_list;                         // it becomes the first free block
    p->free_list = block;
    p->in_use--;
}
A pool of blocks with a free list code/bachelor-1/05-dynamic-memory/exercises/pool.c

A free block holds the address of the next free block in its first bytes, so it must have room for a pointer, and start at an address suitable for one; pool_init rounds the size up to a multiple of sizeof(void *). pool_get and pool_put change two pointers each: constant time. The test tests/pool_test.c takes all five blocks, checks that a sixth is refused, and that the last block returned is the first reused.

Exercise 5.12 ★★★

During a realloc that moves, the old and the new block exist at once. For an array that doubles from capacity 1, prove that the number of slots allocated at the same moment never exceeds 3n3n, where nn is the number of elements after the push that triggered the growth.

Solution

Solution of Exercise 5.12.

A growth from capacity cc to 2c2c happens when cc elements are stored and one more is pushed, so n=c+1n = c + 1. During the move both blocks exist: c+2c=3c<3nc + 2c = 3c < 3n slots. Between moves only one block exists, of capacity below 2n2n. The test tests/test_growth_counts.py checks the bound for every n<5000n < 5000.

5.7 Problem: The leaky phone book

Problem 5.1

Weekend problem — The leaky phone book

The phone book of Listing 5.8 stores contacts in a growable array, under the convention written in its header. Its first version, phonebook_v0.c, and a short session, pbdemo.c, contain five memory errors, numbered in comments. The session was built with the address sanitizer in a mode that reports an error and goes on, so that one run shows them all; the report was saved, and its summary lines extracted. A second program, policies.c, adds contacts to the corrected book under three growth policies.

int book_add(struct book *b, const char *name, long number)
{
    if (b->len == b->cap) {
        size_t cap = next_capacity(b);
        struct contact *bigger = malloc(cap * sizeof *bigger);
        if (bigger == NULL)
            return -1;
        for (size_t i = 0; i < b->len; i++)
            bigger[i] = b->items[i];
        b->copies += (long)b->len;
        free(b->items);
        b->items = bigger;
        b->cap = cap;
    }
    char *copy = malloc(strlen(name));                  // error 1
    if (copy == NULL)
        return -1;
    strcpy(copy, name);
    b->items[b->len].name = copy;
    b->items[b->len].number = number;
    b->len++;
    return 0;
}
int book_remove(struct book *b, const char *name)
{
    for (size_t i = 0; i < b->len; i++)
        if (strcmp(b->items[i].name, name) == 0) {
            free(b->items[i].name);                     // the book owned it
            b->items[i] = b->items[b->len];             // error 2
            b->len--;
            return 0;
        }
    return -1;
}

void book_destroy(struct book *b)
{
    free(b->items);                                     // error 3
    book_init(b, b->policy);
}
Listing 5.19. The first version: adding, removing, destroying code/bachelor-1/05-dynamic-memory/listings/phonebook_v0.c
{
    struct book b;
    book_init(&b, -4);                                    // doubling
    book_add(&b, "Emil Thornworth", 5550101);
    const struct contact *emil = book_find(&b, "Emil Thornworth");
    book_add(&b, "Rosa Yewby", 5550102);
    printf("Emil: %ld\n", emil->number);                  // error 4
    book_add(&b, "Sami Ashworth", 5550103);
    book_add(&b, "Vera Lakewick", 5550104);
    const char *who = book_find(&b, "Rosa Yewby")->name;
    book_remove(&b, "Rosa Yewby");
    printf("removed: first byte %d\n", who[0]);          // error 5
    printf("%zu contacts\n", b.len);
    book_destroy(&b);
    fflush(stdout);
    return 0;
}
Listing 5.20. The session code/bachelor-1/05-dynamic-memory/listings/pbdemo.c
$ gcc -std=c17 -O1 -g -fsanitize=address -fsanitize-recover=address pbdemo.c phonebook_v0.c -o pb
$ ASAN_OPTIONS=halt_on_error=0 ./pb > report.txt 2>&1
$ sed -n 2,6p report.txt
==1000==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x50200000003f at pc 0x7ffff74544bf bp 0x7fffffffeb30 sp 0x7fffffffe2d8
WRITE of size 16 at 0x50200000003f thread T0
    #0 0x7ffff74544be in __interceptor_strcpy ../../../../src/libsanitizer/asan/asan_interceptors.cpp:440
    #1 0x555555555823 in strcpy /usr/include/x86_64-linux-gnu/bits/string_fortified.h:79
    #2 0x555555555823 in book_add ~/session/phonebook_v0.c:39
$ grep -E "^SUMMARY|^Emil|^removed|contacts$" report.txt
SUMMARY: AddressSanitizer: heap-buffer-overflow ../../../../src/libsanitizer/asan/asan_interceptors.cpp:440 in __interceptor_strcpy
SUMMARY: AddressSanitizer: heap-buffer-overflow ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors.inc:466 in __interceptor_strcmp
SUMMARY: AddressSanitizer: heap-use-after-free ~/session/pbdemo.c:12 in main
SUMMARY: AddressSanitizer: heap-buffer-overflow ~/session/phonebook_v0.c:59 in book_remove
SUMMARY: AddressSanitizer: heap-use-after-free ~/session/pbdemo.c:17 in main
Emil: 5550101
removed: first byte 1
3 contacts
SUMMARY: AddressSanitizer: 41 byte(s) leaked in 3 allocation(s).
Output 5.13. The start of the first report, then every summary line and the session’s own output.
$ gcc -std=c17 -O2 -Wall -Wextra -o policies policies.c phonebook.c -lm && ./policies
policy      n    copies    cap  unused
   +16   1000     31248   1008       8
    x2   1000      1023   1024      24
  x1.5   1000      2120   1065      65
   +16  10000   3120000  10000       0
    x2  10000     16383  16384    6384
  x1.5  10000     24261  12137    2137
   +16 100000 312450000 100000       0
    x2 100000    131071 131072   31072
  x1.5 100000    276492 138254   38254
Output 5.14. Copies, final capacity and unused slots for three policies.

Part I — Reading the reports.

  1. The first report is a write of 16 bytes into a block of 15. Which call writes, which line of book_add made the block, and why is it one byte short?
  2. Why does the summary line of that report name strcpy rather than book_add, and how does the start of the report recover the line of book_add?
  3. The second summary is a read by strcmp. Which function calls it, and why is it the same error as the first?
  4. The third summary is a use after free at line 12 of pbdemo.c. Which block was freed, by which call, and why?
  5. The fourth summary is in book_remove. With 4 contacts in a block of capacity 4, which element does b->items[b->len] designate?
  6. The fifth summary is at line 17 of pbdemo.c. What does who point to, and who freed it?
  7. The leak report counts 41 bytes in 3 blocks. Identify the three blocks, and check the total with the lengths of the names and error 1.

Part II — Fixing under the convention.

  1. Fix error 1. Why is strlen(name) + 1 the right size?
  2. Fix error 2, and say which contact the erroneous line lost.
  3. Fix error 3 so that book_destroy frees everything the book holds, in the right order.
  4. Error 4 is in the caller. Which sentence of the convention did it break? Rewrite the session so that it is correct.
  5. Same question for error 5.
  6. With all five fixed, which blocks exist just before book_destroy, and how many free calls does it make?
  7. Why does book_add copy the name instead of keeping the caller’s pointer? Give a caller for whom keeping it would be a bug.

Part III — Growth policies.

  1. For the policy +16 and n=1000n = 1000, recompute the 31 248 copies of Output 5.14.
  2. For doubling and n=1000n = 1000: list the capacities reached and recompute 1023 copies and 24 unused slots.
  3. The policy x1.5 computes the new capacity as ⌈1.5c⌉\lceil 1.5c \rceil. Give its first seven capacities, from 1.
  4. For n=100 000n = 100\,000, by what factor does +16 copy more than doubling? Explain the order of magnitude.
  5. Why does the policy +16 have 0 unused slots for n=10 000n = 10\,000 and n=100 000n = 100\,000?

Part IV — The memory budget.

  1. Let a policy replace a full capacity cc by a capacity CC with rc≤C<rc+1rc \leq C < rc + 1, for a fixed r>1r > 1 (doubling, and x1.5 rounded up, are such policies). Prove that pushing nn elements copies fewer than rn/(r−1)rn/(r-1) elements.
  2. Prove that the unused slots after the last growth are fewer than (r−1)n(r-1)n.
  3. Check both bounds on the rows x2 and x1.5 of Output 5.14.
  4. A contact takes 16 bytes. For n=100 000n = 100\,000, how many bytes does each policy leave unused? Which policy would you choose for a phone with little memory, and which for a server that adds contacts all day?
  5. State the named result of the problem, the growth-factor trade-off.
Solution

Solution of Problem 5.1.

1. strcpy at line 39 writes the 15 characters of "Emil Thornworth" and the final zero byte, 16 bytes, into the block made at line 36 by malloc(strlen(name)), which counts the characters but not the zero.

2. The bad write happens inside the C library’s strcpy, which the sanitizer replaces by a checking version; the summary names the innermost frame. The start of the report shows the next frames: book_add at line 39.

3. book_find (line 49), called at line 10 of the session: strcmp reads the stored name until its zero byte, which was written one byte past the block. Same short block, now read.

4. The array of contacts of capacity 1, which book_add freed at line 32 when it moved the contacts to a block of capacity 2 for Rosa; emil pointed into the old block.

5. Element 4 of a block of 4 contacts: one past its end (64 bytes, then the overflow). The last contact is b->items[b->len - 1].

6. To Rosa’s name, which book_remove freed at line 58, as the convention says it does.

7. The names still in the book when book_destroy ran, which it did not free: Emil Thornworth (15 bytes, error 1), Sami Ashworth (13), and Vera Lakewick (13), 15+13+13=4115 + 13 + 13 = 41. Vera’s name is no longer reachable from the book (question 9), but its block was still allocated.

8. malloc(strlen(name) + 1): a string of ℓ\ell characters occupies ℓ+1\ell + 1 bytes, the last one zero.

9. b->items[i] = b->items[b->len - 1];. With 4 contacts, removing Rosa (index 1) copied the slot past the end into index 1, and the length became 3: the last contact, Vera, fell outside the book, and index 1 holds garbage.

10. for (size_t i = 0; i < b->len; i++) free(b->items[i].name); free(b->items);, then reset the structure: the names first, since their addresses are stored in the array.

11. “Valid only until the next book_add.” Correct: read the number into a variable, long emil_number = emil->number;, before adding, or call book_find again after the addition.

12. “Valid only until the next book_remove”; the name was freed by the removal. Print or copy the name before removing.

13. The array of capacity 4 and the three names: 4 blocks, so 4 calls of free.

14. The book must free its names, so it must own them: a caller’s pointer may point to a local array, to a string literal (which must never be freed), or to a buffer that the caller reuses, like name in the test, which would make every contact share one changing name.

15. Growths at 16,32,…,99216, 32, \dots, 992: m=62m = 62, 16×62×63/2=31 24816 \times 62 \times 63 / 2 = 31\,248.

16. Capacities 1,2,4,…,10241, 2, 4, \dots, 1024; copies 1+2+⋯+512=10231 + 2 + \dots + 512 = 1023; unused 1024−1000=241024 - 1000 = 24.

17. 1,2,3,5,8,12,181, 2, 3, 5, 8, 12, 18.

18. 312 450 000/131 071≈2384312\,450\,000 / 131\,071 \approx 2384. The policy +16 copies about n2/32n^2/32 elements, doubling about 1.3n1.3n: the ratio grows like nn, here about 100 000/42100\,000 / 42.

19. 10 000=625×1610\,000 = 625 \times 16 and 100 000=6250×16100\,000 = 6250 \times 16: the capacity, a multiple of 16, is exactly nn.

20. Let c1<c2<⋯<cmc_1 < c_2 < \dots < c_m be the capacities at which growths happen; each is below nn, and ci+1≥rcic_{i+1} \geq r c_i, so ci≤cm/rm−ic_i \leq c_m / r^{m-i}. The copies are ∑ici≤cm(1+1/r+1/r2+⋯ )=cm r/(r−1)<rn/(r−1)\sum_i c_i \leq c_m (1 + 1/r + 1/r^2 + \cdots) = c_m \, r/(r-1) < rn/(r-1).

21. The last growth, from cmc_m to C<rcm+1C < r c_m + 1, happened when the push number cm+1c_m + 1 arrived, so n≥cm+1n \geq c_m + 1. Unused: C−n<rcm+1−cm−1=(r−1)cm<(r−1)nC - n < r c_m + 1 - c_m - 1 = (r-1)c_m < (r-1)n.

22. x2 (r=2r = 2: copies <2n< 2n, unused <n< n): 1023<20001023 < 2000, 16 383<20 00016\,383 < 20\,000, 131 071<200 000131\,071 < 200\,000; 2424, 63846384, 31 07231\,072 below nn. x1.5 (r=1.5r = 1.5: copies <3n< 3n, unused <n/2< n/2): 2120<30002120 < 3000, 24 261<30 00024\,261 < 30\,000, 276 492<300 000276\,492 < 300\,000; 65<50065 < 500, 2137<50002137 < 5000, 38 254<50 00038\,254 < 50\,000.

23. +16: 0 bytes; x2: 31 072×16=497 15231\,072 \times 16 = 497\,152 bytes; x1.5: 38 254×16=612 06438\,254 \times 16 = 612\,064 bytes. For this nn, x1.5 happens to waste more than x2: the bounds are worst cases, and where nn falls between two capacities decides the actual waste. On a small device, the bound n/2n/2 of x1.5 (or growth by a fixed step, if the list stays short) is the safer choice; on a server that adds all day, doubling makes the fewest copies.

24. The growth-factor trade-off. A growable array whose capacity cc becomes CC with rc≤C<rc+1rc \leq C < rc + 1 copies fewer than rn/(r−1)rn/(r-1) elements and keeps fewer than (r−1)n(r-1)n unused slots for nn elements: doubling, below 2n2n and nn; x1.5, below 3n3n and n/2n/2. A larger factor copies less and wastes more. Growth by a fixed kk wastes fewer than kk slots but copies about n2/(2k)n^2/(2k) elements. The nine rows measured for n=103n = 10^3, 10410^4 and 10510^5 all respect these bounds.

Terms defined in this chapter

See all 1050 terms in the glossary