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;
}
$ 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 ...
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;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o nullcheck nullcheck.c -lm && ./nullcheck
malloc(9223372036854775807) returned NULL
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;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o realloc_grow realloc_grow.c -lm && ./realloc_grow
0 10 20 30 40 50 60 70
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.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;
}
$ 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
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;
}
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
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;
}
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
free is reported, with the first. Some lines are left out.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;
}
$ 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];
| ~~~~~~^~~~~~~~~~~
-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:
- whether a returned block belongs to the caller, who must free it (as for
malloc); - whether a pointer it receives is kept (the function takes charge of the block) or only borrowed during the call;
- 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
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);
}
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
Definition 5.5 (Growth factor)
A growable array whose capacity, when full, is multiplied by a fixed has growth factor . The alternative is to add a fixed number of slots at each growth.
Growth costs copies: moving from a full block of capacity copies elements. With growth by one slot, reaching elements copies elements; with doubling, it copies up to the last power of two below , fewer than . 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;
}
$ 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
Proposition 5.6 (Doubling copies fewer than elements)
A growable array that starts with capacity 1 and doubles its capacity when full copies fewer than elements in all while elements are pushed.
Proof. The growths happen at capacities , where is the largest power of two below (a growth happens when the array is full and one more element arrives, so its capacity is less than ). They copy elements, and gives . If , there is no growth and no copy. ∎
So each push costs, on average over the whole sequence, fewer than two copies, however large 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.
5.5 Two-dimensional arrays of unknown size
A grid of numbers known only at run time can be stored in two ways. The first allocates a table of row pointers, then one block per row: g[i][j] works as for a static array, but there are 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;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o grid_rows grid_rows.c -lm && ./grid_rows
g[2][4] = 1.5, 3 + 1 blocks
Definition 5.7 (Linearised array)
A linearised array stores the elements of an grid in a single block of elements, in row-major order: element is at index .
#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;
}
$ 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
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;
}
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 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;
}
Solution
Solution of Exercise 5.2.
The members take 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
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;
}
realloc code/bachelor-1/05-dynamic-memory/listings/exo_realloc.cSolution
Solution of Exercise 5.3.
realloc keeps the first three values, wherever the block goes; b[3] . 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
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;
}
Solution
Solution of Exercise 5.4.
When fopen fails, the function returns 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;
}
realloc code/bachelor-1/05-dynamic-memory/listings/exo_realloc_bad.cSolution
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;
}
$ 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
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;
}
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);
}
When row cannot be allocated, rows 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 and adds slots when full. Show that pushing elements copies elements, where , roughly . Check it against the +16 row of Output 5.14 for .
Solution
Solution of Exercise 5.9.
A growth happens when the array is full at a capacity below : at capacities with , that is . They copy elements, and gives about . For and : and , 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 , and show that the bound cannot be replaced by for any .
Solution
Solution of Exercise 5.10.
The growths happen at capacities , all below , and copy elements. For and , the copies are , and tends to 2: no bound holds for all .
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 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 , where is the number of elements after the push that triggered the growth.
Solution
Solution of Exercise 5.12.
A growth from capacity to happens when elements are stored and one more is pushed, so . During the move both blocks exist: slots. Between moves only one block exists, of capacity below . The test tests/test_growth_counts.py checks the bound for every .
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);
}
{
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;
}
$ 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).
$ 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
Part I — Reading the reports.
- The first report is a write of 16 bytes into a block of 15. Which call writes, which line of
book_addmade the block, and why is it one byte short? - Why does the summary line of that report name
strcpyrather thanbook_add, and how does the start of the report recover the line ofbook_add? - The second summary is a read by
strcmp. Which function calls it, and why is it the same error as the first? - The third summary is a use after free at line 12 of
pbdemo.c. Which block was freed, by which call, and why? - The fourth summary is in
book_remove. With 4 contacts in a block of capacity 4, which element doesb->items[b->len]designate? - The fifth summary is at line 17 of
pbdemo.c. What doeswhopoint to, and who freed it? - 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.
- Fix error 1. Why is
strlen(name) + 1the right size? - Fix error 2, and say which contact the erroneous line lost.
- Fix error 3 so that
book_destroyfrees everything the book holds, in the right order. - Error 4 is in the caller. Which sentence of the convention did it break? Rewrite the session so that it is correct.
- Same question for error 5.
- With all five fixed, which blocks exist just before
book_destroy, and how manyfreecalls does it make? - Why does
book_addcopy the name instead of keeping the caller’s pointer? Give a caller for whom keeping it would be a bug.
Part III — Growth policies.
- For the policy
+16and , recompute the 31 248 copies of Output 5.14. - For doubling and : list the capacities reached and recompute 1023 copies and 24 unused slots.
- The policy x1.5 computes the new capacity as . Give its first seven capacities, from 1.
- For , by what factor does
+16copy more than doubling? Explain the order of magnitude. - Why does the policy
+16have 0 unused slots for and ?
Part IV — The memory budget.
- Let a policy replace a full capacity by a capacity with , for a fixed (doubling, and x1.5 rounded up, are such policies). Prove that pushing elements copies fewer than elements.
- Prove that the unused slots after the last growth are fewer than .
- Check both bounds on the rows x2 and x1.5 of Output 5.14.
- A contact takes 16 bytes. For , 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?
- 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), . 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 characters occupies 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. Capacities ; copies ; unused .
17. .
18. . The policy +16 copies about elements, doubling about : the ratio grows like , here about .
19. and : the capacity, a multiple of 16, is exactly .
20. Let be the capacities at which growths happen; each is below , and , so . The copies are .
21. The last growth, from to , happened when the push number arrived, so . Unused: .
22. x2 (: copies , unused ): , , ; , , below . x1.5 (: copies , unused ): , , ; , , .
23. +16: 0 bytes; x2: bytes; x1.5: bytes. For this , x1.5 happens to waste more than x2: the bounds are worst cases, and where falls between two capacities decides the actual waste. On a small device, the bound 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 becomes with copies fewer than elements and keeps fewer than unused slots for elements: doubling, below and ; x1.5, below and . A larger factor copies less and wastes more. Growth by a fixed wastes fewer than slots but copies about elements. The nine rows measured for , and all respect these bounds.