---
title: "Memory Management and Garbage Collection"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 9
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/9-memory-management-and-garbage-collection
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 9 — Memory Management and Garbage Collection

A C program asks for memory with `malloc` and gives it back with `free`; a Python, Java or Lisp program only asks, and something else decides when a block can be reused. This chapter opens both boxes. It writes the [allocator](#def-b3-garbage-collection-allocator) behind `malloc` and measures how its free memory crumbles into pieces; it then writes the three classic ways of finding the blocks a program can no longer use (counting references, tracing from the roots, and copying), proves what each guarantees, and measures what each costs on a model of the town’s server. A last section asks what a language without a collector, such as Rust, pays instead.

**You already know.**

The Year 1 volume’s heap is the region from which `malloc` hands out blocks while a program runs; `free` returns one. A block the program can no longer reach but never freed is a memory leak; a pointer used after its block was freed is dangling.

![A magnetic-core memory plane: 32 by 32 ferrite rings at the crossings of the wires, each holding one bit, 1024 bits in all, or 128 bytes. Programs that build lists and trees as they run must reuse memory: a whole plane holds only eight of this chapter’s cells.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-garbage-collection/img-be4c40a4c24d.jpg)

*A magnetic-core memory plane: 32 by 32 ferrite rings at the crossings of the wires, each holding one bit, 1024 bits in all, or 128 bytes. Programs that build lists and trees as they run must reuse memory: a whole plane holds only eight of this chapter’s cells.*

## 9.1 Allocators

**Definition 9.1 (Allocator, free list, first fit, best fit, boundary tag).**

An *allocator* manages a region of memory: it hands out blocks on request and takes them back. Its *free list* is the set of its free blocks, found by walking all the blocks in address order or linked through the free blocks themselves. Given a request, *first fit* takes the first free block large enough, in address order; *best fit* takes the smallest free block large enough. A *boundary tag* is a word at each end of a block that records its size and whether it is in use.

[Listing 9.1](#lst-b3-garbage-collection-tags) lays the arena out: the blocks tile it from one end to the other, so the size in a block’s header leads to the next block, and the footer at its end lets the block after it find the start of this one. A used word at each end of the arena, the prologue and the epilogue, saves every walk from testing the bounds.

```c
/* arena.c -- every block, free or used, starts and ends with a boundary tag: its size in
   bytes, with the low bit set when the block is in use. The blocks tile the arena. */
#include "arena.h"

#define W sizeof(size_t)
#define N (ARENA_BYTES / W)
#define MIN_BLOCK 32
static size_t heap[N];
static arena_fit fit;

static size_t size(size_t i) { return heap[i] & ~(size_t)1; }
static int used(size_t i) { return heap[i] & 1; }
static size_t next(size_t i) { return i + size(i) / W; }
static void tag(size_t i, size_t bytes, size_t in_use)
{
    heap[i] = heap[i + bytes / W - 1] = bytes | in_use;  /* header and footer */
}
```

***Listing 9.1.** [Boundary tags](#def-b3-garbage-collection-allocator). Sizes are multiples of 16 bytes, so the lowest bit of a tag is free to say whether the block is in use. code/bachelor-3/09-garbage-collection/listings/arena.c*

```c
void arena_init(arena_fit policy)
{
    fit = policy;
    heap[0] = 1;             /* prologue: a footer in use, so nothing merges past the start */
    tag(1, (N - 2) * W, 0);  /* one free block, the whole arena */
    heap[N - 1] = 1;         /* epilogue: a header in use of size 0, where every walk stops */
}

size_t first_fit(size_t bytes)
{
    for (size_t i = 1; size(i) > 0; i = next(i))
        if (!used(i) && size(i) >= bytes) return i;
    return 0;
}

size_t best_fit(size_t bytes)
{
    size_t best = 0;
    for (size_t i = 1; size(i) > 0; i = next(i))
        if (!used(i) && size(i) >= bytes && (best == 0 || size(i) < size(best))) best = i;
    return best;
}
```

***Listing 9.2.** An empty arena, and the two placement policies, each a walk over the blocks. code/bachelor-3/09-garbage-collection/listings/arena.c*

A request for $n$ bytes needs a block of $n$ plus two tags, rounded up to 16 bytes. If the chosen free block is larger, the [allocator](#def-b3-garbage-collection-allocator) splits it and the tail stays free; if the tail would be too small to hold even its own tags and a little payload, the request takes the whole block ([Listing 9.3](#lst-b3-garbage-collection-allocfree)).

**Definition 9.2 (Fragmentation, coalescing of free blocks).**

*Internal fragmentation* is memory inside used blocks that the program did not ask for: tags and rounding. *External fragmentation* is free memory split into blocks too small to serve a request, although their total would; we measure it as $1 - \text{largest free block}/\text{total free}$. *Coalescing of free blocks* merges a freed block with the free blocks next to it in memory, so that no two free blocks touch.

```c
void *arena_alloc(size_t n)
{
    size_t bytes = arena_block_bytes(n), i = fit(bytes);
    if (i == 0) return NULL;
    size_t rest = size(i) - bytes;
    if (rest >= MIN_BLOCK) {  /* split: the tail stays free */
        tag(i, bytes, 1);
        tag(i + bytes / W, rest, 0);
    } else {
        tag(i, size(i), 1);   /* too small a tail: the request takes the whole block */
    }
    return &heap[i + 1];
}

void arena_free(void *p)
{
    size_t i = (size_t)((size_t *)p - heap) - 1, bytes = size(i);
    if (!used(next(i))) bytes += size(next(i));  /* coalesce with the next block */
    if (!used(i - 1)) {  /* and with the previous block, whose footer is at i - 1 */
        i -= size(i - 1) / W;
        bytes += size(i);
    }
    tag(i, bytes, 0);
}
```

***Listing 9.3.** Allocating with a split, and freeing with coalescing on both sides. The footer at $i - 1$ gives the previous block’s size, so its start, in constant time. code/bachelor-3/09-garbage-collection/listings/arena.c*

![Freeing the middle block of 96 bytes. Its neighbours on both sides are free: the footer just before it gives the start of the block of 64, and its own size gives the header of the block of 128. The three become one block of 288 bytes; the grey boundary tags at its two ends are rewritten, the ones in between are simply forgotten.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-garbage-collection/fig-914420d6b47e.svg)

*Freeing the middle block of 96 bytes. Its neighbours on both sides are free: the footer just before it gives the start of the block of 64, and its own size gives the header of the block of 128. The three become one block of 288 bytes; the grey [boundary tags](#def-b3-garbage-collection-allocator) at its two ends are rewritten, the ones in between are simply forgotten.*

Which policy fragments less depends on the program. [Output 9.1](#out-b3-garbage-collection-frag) runs one seeded workload of 20,000 steps under each: 280 slots, each either empty or holding a block, are allocated and freed at random, with mostly small requests and one in five a buffer of 400 to 2,000 bytes, in an arena of 64 KiB.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o frag frag.c arena.c -lm && ./frag
first fit failed   17, with at least  6208 B free each time
          used 46368 B in 157 blocks (internal  7.8 %)
          free 19152 B in  32 blocks, largest 10016 B (external 47.7 %)
          free blocks by size: <64 17, <128 3, <256 1, <512 2, <1K 4, <2K 4, <4K 0, more 1
best fit  failed   11, with at least  9824 B free each time
          used 41008 B in 145 blocks (internal  8.3 %)
          free 24512 B in  22 blocks, largest  5472 B (external 77.7 %)
          free blocks by size: <64 4, <128 3, <256 5, <512 2, <1K 1, <2K 3, <4K 2, more 2
```

***Output 9.1.** One workload under [first fit](#def-b3-garbage-collection-allocator) and [best fit](#def-b3-garbage-collection-allocator): the requests that found no free block large enough, and the arena at the end.*

[Best fit](#def-b3-garbage-collection-allocator) refused 11 requests and [first fit](#def-b3-garbage-collection-allocator) 17, all of them buffers of at most 2,016 bytes, although each time at least 6,208 bytes were free: [external fragmentation](#def-b3-garbage-collection-fragmentation), not a lack of memory. [First fit](#def-b3-garbage-collection-allocator) ends with 17 free blocks under 64 bytes, slivers too small for almost any request. [Internal fragmentation](#def-b3-garbage-collection-fragmentation) is under 10 %, the price of the tags and the rounding. A real [allocator](#def-b3-garbage-collection-allocator) keeps a separate [free list](#def-b3-garbage-collection-allocator) per size class (*segregated lists*), so that a small request never searches the large blocks and blocks of one size sit together; for a request of a given class, its search is constant time.

## 9.2 Reference counting

From here on the program does not call `free`: the runtime must find out by itself when a block can never be used again.

**Definition 9.3 (Reference counting).**

*Reference counting* stores in each object its *reference count*, the number of references to it held by variables and by other objects. Every copy of a reference increments the count of its target, every overwritten or discarded reference decrements it, and an object whose count reaches 0 is freed at once, decrementing the counts of the objects it refers to.

CPython counts references. `sys.getrefcount` shows a count one higher than expected, because its own argument is a reference while it runs ([Listing 9.4](#lst-b3-garbage-collection-refcount)).

```python
"""refcount.py -- CPython counts references; its cycle collector finds what
counting misses."""
import gc
import sys


class Loan:
    def __init__(self, title):
        self.title, self.other = title, None

    def __del__(self):
        print(f"  freed {self.title}")


a = Loan("Dune")
print("one name:        ", sys.getrefcount(a))  # one more: the argument itself
b = a
shelf = [a, a]
print("three more:      ", sys.getrefcount(a))
del b
shelf.clear()
print("back to one name:", sys.getrefcount(a))
print("del a:")
del a  # the count drops to zero: freed at once

gc.disable()  # no automatic cycle collection while we watch
x, y = Loan("Emma"), Loan("Ulysses")
x.other, y.other = y, x  # a cycle: each keeps the other's count at 1
print("del x, y:")
del x, y
print("  (nothing freed)")
print("gc.collect():")
print("  unreachable objects found:", gc.collect())
```

***Listing 9.4.** Counts rising and falling, an object freed the moment its count reaches 0, and a cycle that counting cannot free. code/bachelor-3/09-garbage-collection/listings/refcount.py*

```
$ python refcount.py
one name:         2
three more:       5
back to one name: 2
del a:
  freed Dune
del x, y:
  (nothing freed)
gc.collect():
  freed Emma
  freed Ulysses
  unreachable objects found: 2
```

***Output 9.2.** `Dune` is freed by `del a`, before the next line runs. `Emma` and `Ulysses` survive their names: each keeps the other’s count at 1, until the cycle collector finds them unreachable.*

The good side of counting is in the first half of the output: memory comes back at a known moment, in small steps, with no pause. The bad side is the second half: two objects that refer to each other keep their counts above 0 forever, whether the program can reach them or not. CPython therefore adds a tracing collector for cycles, the subject of the next section, and `gc.collect` reports the number of unreachable objects it found. Counting has two other costs: every assignment of a reference writes two counts, which is costly when several threads share objects, and freeing a long list frees its cells one after the other in one go. *Deferred* counting ignores the references held in local variables and checks for zero counts now and then; *weighted* counting splits a weight between copies of a reference so that copying it does not touch the target.

## 9.3 Tracing: mark and sweep

**Definition 9.4 (Root set, reachable object, garbage).**

The *root set* of a running program is the set of references it holds outside the heap: in its variables, its registers and its call stack. An object is *reachable* if a path of references leads to it from a root. A heap object that is not reachable is *garbage*: no future step of the program can read it.

[Garbage](#def-b3-garbage-collection-reachability) is a safe approximation of “never used again”: an unreachable object is certainly never used, while a [reachable](#def-b3-garbage-collection-reachability) one may or may not be. A collector frees only [garbage](#def-b3-garbage-collection-reachability), so it never frees an object the program will use.

The collectors of this chapter manage a heap of *cells* (`heap.h`), each with an integer and two references, which is enough for lists, trees and arbitrary graphs. Their program is a model of the town’s server (`server.h`): each request builds a list of short-lived work, then a session, a list of a few cells kept in a table of the most recent sessions, the roots. Every reference the program keeps across an allocation is in that table, since an allocation may collect.

**Definition 9.5 (Garbage collection, mark and sweep, tri-colour invariant).**

*Garbage collection* is the automatic freeing of [garbage](#def-b3-garbage-collection-reachability). A *mark-and-sweep* collector marks every object [reachable](#def-b3-garbage-collection-reachability) from the roots, then sweeps the whole heap and frees every object left unmarked. During marking, an object is *white* if not yet reached, *grey* if reached but its references not yet examined, *black* if reached and all its references examined. The *tri-colour invariant* says that no black object refers to a white one.

```c
static void mark(void)
{
    int top = 0;
    for (int r = 0; r < nroots; r++)
        if (roots[r] != NIL && heap[roots[r]].meta == WHITE) {
            heap[roots[r]].meta = MARKED;  /* grey: marked, on the stack */
            stack[top++] = roots[r];
        }
    while (top > 0) {
        int c = stack[--top];             /* black once its references are pushed */
        gc_stats.visited++;
        for (int k = 0; k < 2; k++) {
            int d = heap[c].ref[k];
            if (d != NIL && heap[d].meta == WHITE) {
                heap[d].meta = MARKED;
                stack[top++] = d;
            }
        }
    }
}

static void sweep(void)
{
    for (int c = 0; c < size; c++) {
        if (heap[c].meta == MARKED) {
            heap[c].meta = WHITE;         /* ready for the next collection */
        } else if (heap[c].meta == WHITE) {  /* unreachable: garbage */
            heap[c] = (struct cell){FREE, 0, {free_list, NIL}};
            free_list = c;
            gc_stats.swept++;
        }
    }
}
```

***Listing 9.5.** Mark with an explicit stack: a grey cell is a marked cell still on the stack. Sweep visits every cell of the heap. code/bachelor-3/09-garbage-collection/listings/marksweep.c*

**Theorem 9.6 (Marking is correct).**

The marking loop of [Listing 9.5](#lst-b3-garbage-collection-marksweep) keeps the [tri-colour invariant](#def-b3-garbage-collection-marksweep), and it stops with every [reachable](#def-b3-garbage-collection-reachability) cell black and every other cell white.

**Proof.** Grey cells are exactly the cells on the stack: a cell is marked when it is pushed and becomes black when it is popped and its two references examined. At the start nothing is black. One iteration pops a grey cell $c$ and examines its references; every white one is marked and pushed, so becomes grey. Afterwards $c$ is black and refers to no white cell; no other black cell changed or lost a black neighbour’s colour, since colours only go from white to grey to black. So the invariant holds after every iteration. Each cell is pushed at most once, when it stops being white, so the loop stops, with an empty stack: no grey cell. Take a [reachable](#def-b3-garbage-collection-reachability) cell $x$ and a path $r = x_0, x_1, \dots, x_k = x$ from a root. $x_0$ was made grey by the first loop, so it is black at the end. If $x_i$ is black, $x_{i+1}$ is not white by the invariant, and not grey since none is left: it is black. By induction $x$ is black. Conversely a cell becomes grey only when reached from a root or from a grey cell, so every marked cell is [reachable](#def-b3-garbage-collection-reachability). ∎

The invariant is what makes marking safe to interleave with the program, the subject of collectors that run alongside it: the program may change references while marking is under way, and it must then never store a reference to a white cell into a black one without telling the collector (exercise [9.11](#exo-b3-garbage-collection-11) meets the same constraint in another form). The explicit stack can hold every cell of the heap; a collector that cannot afford such a stack marks with a bounded one, and when it overflows, it rescans the heap for marked cells whose references still point to white ones.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o ms_demo ms_demo.c marksweep.c -lm && ./ms_demo
collection 1 during request   93: marked  744, swept 2256
collection 2 during request  164: marked 1208, swept 1792
collection 3 during request  220: marked 1208, swept 1792
collection 4 during request  276: marked 1208, swept 1792
collection 5 during request  332: marked 1208, swept 1792
collection 6 during request  388: marked 1208, swept 1792
2000 requests: 64000 cells allocated, 34 collections, 40608 marked, 61392 swept
```

***Output 9.3.** The server on a heap of 3,000 cells: 150 sessions of 8 cells, each closed into a cycle, and 24 cells of work per request. In the steady state a collection marks the 1,208 live cells and sweeps the other 1,792.*

Every session is a cycle, and the collector frees them anyway, since a cycle that no root reaches is [garbage](#def-b3-garbage-collection-reachability) like any other cell. The cost of one collection is the number of [reachable](#def-b3-garbage-collection-reachability) cells for marking plus the size of the whole heap for sweeping; between two collections, the program allocates the cells that were swept.

## 9.4 Copying and generational collection

**Definition 9.7 (Copying collector, forwarding pointer).**

A *copying collector* splits the heap into two halves, *from-space*, where the program allocates, and *to-space*, kept empty. A collection copies every [reachable](#def-b3-garbage-collection-reachability) cell of from-space into to-space, updates every reference to point at the copies, and swaps the two halves’ roles. When a cell is copied, its old place receives a *forwarding pointer*, the address of the copy, so that later references to it are redirected instead of copying it twice.

Cheney’s algorithm does it breadth first with no stack: the cells copied into to-space form the queue. Two indices walk to-space: `next`, where the next copy goes, and `scan`, the first copied cell whose references have not been updated. The cells before `scan` are black, those between `scan` and `next` grey, and from-space cells without a [forwarding pointer](#def-b3-garbage-collection-copying) white ([Listing 9.6](#lst-b3-garbage-collection-cheney)).

```c
static int forward(int c, int *next)  /* the cell's new index, copying it the first time */
{
    if (c == NIL) return NIL;
    if (from[c].meta == NIL) {      /* not copied yet */
        to[*next] = from[c];
        from[c].meta = (*next)++;   /* leave a forwarding pointer behind */
        gc_stats.visited++;
    }
    return from[c].meta;
}

static void collect(void)
{
    int scan = 0, next = 0;
    for (int r = 0; r < nroots; r++) roots[r] = forward(roots[r], &next);
    while (scan < next) {           /* to-space cells between scan and next are grey */
        for (int k = 0; k < 2; k++) to[scan].ref[k] = forward(to[scan].ref[k], &next);
        scan++;
    }
    struct cell *t = from;
    from = to;
    to = t;
    top = next;
    gc_stats.collections++;
}
```

***Listing 9.6.** Cheney’s algorithm: forward the roots, then scan to-space until the scan index catches up with the free index. code/bachelor-3/09-garbage-collection/listings/cheney.c*

![Cheney’s algorithm on the graph of exercise , after the root A was copied and scanned. A’s references were forwarded: B and C were copied and their old places hold forwarding pointers (to cells 1 and 2). E, garbage, is never touched. Scanning B next will copy D to cell 3.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-garbage-collection/fig-76e15b2e794c.svg)

*Cheney’s algorithm on the graph of exercise [9.8](#exo-b3-garbage-collection-8), after the root A was copied and scanned. A’s references were forwarded: B and C were copied and their old places hold [forwarding pointers](#def-b3-garbage-collection-copying) (to cells 1 and 2). E, [garbage](#def-b3-garbage-collection-reachability), is never touched. Scanning B next will copy D to cell 3.*

**Theorem 9.8 (Cheney’s algorithm).**

A collection copies each cell [reachable](#def-b3-garbage-collection-reachability) from the roots exactly once, and no other, leaves every reference pointing at the copy of its target, and does work proportional to the number of [reachable](#def-b3-garbage-collection-reachability) cells plus the number of roots.

**Proof.** A cell is copied only by `forward`, the first time a reference to it is forwarded; the [forwarding pointer](#def-b3-garbage-collection-copying) it leaves makes every later call return the same copy. Each copy is scanned once, when `scan` passes it, and each of its two references is then forwarded, so the set of copied cells is closed under references and contains the roots’ targets: it contains every [reachable](#def-b3-garbage-collection-reachability) cell. Conversely a cell is copied only when a root or a copied cell refers to it, so every copied cell is [reachable](#def-b3-garbage-collection-reachability). Every reference in to-space and every root was forwarded, so points at a copy. The work is one forward per root and two per copied cell, each in constant time. [Garbage](#def-b3-garbage-collection-reachability) is never examined. ∎

This is the [copying collector](#def-b3-garbage-collection-copying)’s great property: its cost does not depend on the amount of [garbage](#def-b3-garbage-collection-reachability). [Output 9.4](#out-b3-garbage-collection-cheney) runs the server’s workload of [Output 9.3](#out-b3-garbage-collection-ms) under it, on the same 3,000 cells.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o cheney_demo cheney_demo.c cheney.c -lm && ./cheney_demo
collection 1 during request   46: copied  372
collection 2 during request   82: copied  660
collection 3 during request  108: copied  876
collection 4 during request  127: copied 1020
collection 5 during request  142: copied 1140
collection 6 during request  154: copied 1204
2000 requests: 64000 cells allocated, 211 collections, 253732 copied
```

***Output 9.4.** The same workload on a copying heap of 3,000 cells, so 1,500 per half. A collection copies the live cells and nothing else.*

On the same memory the [copying collector](#def-b3-garbage-collection-copying) runs 211 collections instead of 34, because the program has only half of it: after copying 1,204 live cells, only 296 are free in from-space. The weekend problem prices that half: exercise [9.10](#exo-b3-garbage-collection-10) proves that with $L$ live cells in a heap of $H$ cells, the [copying collector](#def-b3-garbage-collection-copying) copies $L/(H/2 - L)$ cells per cell allocated.

Most objects die young: the work list of a request is [garbage](#def-b3-garbage-collection-reachability) before the request ends. *Generational* collectors bet on this *generational hypothesis*: collecting the young objects often and the old ones rarely spends little time on objects that survive.

**Definition 9.9 (Generational collection, write barrier, remembered set).**

A *generational collector* allocates in a small *nursery* and collects it alone in a *minor* collection, which moves its survivors into an old generation (*promotion*); a *major* collection collects the whole heap. The *remembered set* holds the old objects that may refer to nursery objects; a minor collection treats them as roots. A *write barrier* is code run at every store of a reference into an object; here, it adds the object to the remembered set when an old object receives a reference to a young one.

Without the [remembered set](#def-b3-garbage-collection-generational), a minor collection would have to trace the whole old generation to find the references into the nursery, and would no longer be minor. In `gen.c` a minor collection is Cheney’s loop applied to the nursery only, copying into the free end of the old generation ([Listing 9.7](#lst-b3-garbage-collection-gen)); a reference to an old cell is left as it is.

```c
static int copy(int c, int *next, int all)  /* forward c to *next if it must move */
{
    if (c == NIL || !(all || young(c))) return c;
    if (mem[c].meta == NIL) {
        mem[*next] = mem[c];
        mem[c].meta = (*next)++;
    }
    return mem[c].meta;
}

static void scan_from(int scan, int *next, int all)  /* Cheney's loop */
{
    for (int r = 0; r < nroots; r++) roots[r] = copy(roots[r], next, all);
    for (; scan < *next; scan++)
        for (int k = 0; k < 2; k++) mem[scan].ref[k] = copy(mem[scan].ref[k], next, all);
}

static void minor(void)  /* nursery -> old */
{
    int start = top;
    for (int i = 0; i < nremembered; i++)  /* the remembered cells are roots too */
        for (int k = 0; k < 2; k++)
            mem[remembered[i]].ref[k] = copy(mem[remembered[i]].ref[k], &top, 0);
    nremembered = 0;
    scan_from(start, &top, 0);
    promoted += top - start;
    young_top = 2 * old;
    minors++;
}
```

***Listing 9.7.** The [generational collector](#def-b3-garbage-collection-generational)’s two pieces of Cheney: `copy` moves a cell only if it is young, or in a major collection; a minor collection starts from the remembered cells and the roots. code/bachelor-3/09-garbage-collection/listings/gen.c*

![Two generations. The store of a reference to the young cell y into the old cell s goes through the write barrier, which adds s to the remembered set. The next minor collection starts from the roots and from s, so it promotes y; the grey cell, which nothing refers to, is never examined.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-garbage-collection/fig-975f665b41dc.svg)

*Two generations. The store of a reference to the young cell $y$ into the old cell $s$ goes through the [write barrier](#def-b3-garbage-collection-generational), which adds $s$ to the [remembered set](#def-b3-garbage-collection-generational). The next minor collection starts from the roots and from $s$, so it promotes $y$; the grey cell, which nothing refers to, is never examined.*

The workload run here has no cyclic sessions, so the server never stores into a cell after creating it: a new cell can only refer to older ones and its [remembered set](#def-b3-garbage-collection-generational) stays empty; exercise [9.11](#exo-b3-garbage-collection-11) writes the barrier for a program that does store. [Output 9.5](#out-b3-garbage-collection-gen) runs the weekend problem’s workload, with 2,000 live cells, under the [generational collector](#def-b3-garbage-collection-generational) with 12,000 cells in all.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o gen_demo gen_demo.c gen.c -lm && ./gen_demo
 nursery   minor   major  promoted  copied major  copied/alloc
     250    1257      22     83416         44000         0.398
     500     616      23     78848         46072         0.390
    1000     291      28     73916         56112         0.406
    2000     121      38     60500         76000         0.427
```

***Output 9.5.** The [generational collector](#def-b3-garbage-collection-generational) with nurseries of 250 to 2,000 cells: minor and major collections, cells promoted by minors and copied by majors, and all copies per cell allocated.*

The [copying collector](#def-b3-garbage-collection-copying) on the same 12,000 cells copies 0.492 cells per cell allocated ([Output 9.7](#out-b3-garbage-collection-pbcopy) below); the generational one 0.390 to 0.427. The gain is modest because the hypothesis is only three quarters true here: 4 of every 16 cells belong to a session, which lives for the next 500 requests, so every minor collection promotes them, and the old generation fills with sessions that die there. When nearly everything dies young, minor collections copy almost nothing and the gain is large; the program decides.

## 9.5 Memory safety without a collector

The Year 2 volume’s Rust frees a value when its single owner goes out of scope, which the compiler checks: no counts, no tracing, and no pause. For a value with several owners, Rust offers `Rc`, a reference-counted pointer, with the weakness of every count: a cycle between `Rc` pointers is never freed. Its remedy is `Weak`, a reference that does not count: `Weak::upgrade` returns `None` once the value is gone ([Listing 9.8](#lst-b3-garbage-collection-rc)).

```rust
fn main() {
    println!("strong cycle:");
    {
        let (ann, bob) = (member("Ann"), member("Bob"));
        *ann.friend.borrow_mut() = Some(Rc::clone(&bob));
        *bob.friend.borrow_mut() = Some(Rc::clone(&ann));
        println!("  counts {} {}", Rc::strong_count(&ann), Rc::strong_count(&bob));
    } // the two locals go; each count falls to 1, never to 0
    println!("  (end of scope: nothing dropped)");

    println!("weak back pointer:");
    let cleo = member("Cleo");
    {
        let dan = member("Dan");
        *cleo.friend.borrow_mut() = Some(Rc::clone(&dan));
        *dan.sponsor.borrow_mut() = Rc::downgrade(&cleo);
        println!("  counts {} {}, weak {}", Rc::strong_count(&cleo), Rc::strong_count(&dan),
                 Rc::weak_count(&cleo));
    }
    let alive = cleo.friend.borrow().as_ref().map(|d| d.sponsor.borrow().upgrade().is_some());
    println!("  Dan's sponsor still there: {:?}", alive);
    drop(cleo); // Cleo's count reaches 0: Cleo dropped, then Dan
    println!("end of main");
}
```

***Listing 9.8.** Two members who are each other’s friend are never dropped. A member who holds his sponsor by a `Weak` pointer does not keep her alive. code/bachelor-3/09-garbage-collection/listings/rc_cycle.rs*

```
$ rustc --edition 2021 -O -o rc_cycle rc_cycle.rs && ./rc_cycle
strong cycle:
  counts 2 2
  (end of scope: nothing dropped)
weak back pointer:
  counts 1 2, weak 1
  Dan's sponsor still there: Some(true)
  drop Cleo
  drop Dan
end of main
```

***Output 9.6.** Ann and Bob leak: nothing is printed when their scope ends. Cleo and Dan are dropped as soon as Cleo’s last strong count goes.*

Rust’s documentation gives the rule for a tree: strong pointers from a parent to its children, weak ones from a child back to its parent. A third way avoids per-object freeing altogether: an *arena*, a region in which a computation allocates freely and which is freed in one step when the computation ends, as a compiler does with a whole syntax tree. [Table 9.1](#tab-b3-garbage-collection-costs) sums up what each strategy costs.

| strategy | cost on each pointer store | cost of reclaiming | cycles | when memory returns |
| --- | --- | --- | --- | --- |
| manual `free` | none | constant per block | the programmer’s job | when the program says |
| counting | two counts updated | constant per object | leak | at once |
| [mark and sweep](#def-b3-garbage-collection-marksweep) | none | live objects + whole heap | freed | at a collection |
| copying | none | live objects only; half the memory idle | freed | at a collection |
| generational | a [write barrier](#def-b3-garbage-collection-generational) | live young objects, rare majors | freed | at a collection |
| ownership | none (checked by the compiler) | constant per object | impossible without `Rc` | end of the owner’s scope |
| arena | none | one step for the arena | freed with it | when the arena goes |

***Table 9.1.** What each way of managing memory costs, and when.*

**History — Collectors.**

Two papers of 1960 on list processing stand at the start: John McCarthy’s *Recursive functions of symbolic expressions and their computation by machine* in April, and George Collins’s *A method for overlapping and erasure of lists* in December. C. J. Cheney published his nonrecursive list compacting algorithm in November 1970. Edsger Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten and E. F. M. Steffens published on-the-fly [garbage collection](#def-b3-garbage-collection-marksweep) in 1978. Henry Lieberman and Carl Hewitt described a real-time [garbage](#def-b3-garbage-collection-reachability) collector based on the lifetimes of objects in 1983, and David Ungar generation scavenging in 1984.

## 9.6 Exercises

**Exercise 9.1 ★.**

An arena holds, in address order, free blocks of 96, 48, 160 and 64 bytes, separated by used blocks, then one large free block. Requests of 40, 24, 130 and 80 bytes arrive in that order; each needs a block of its size plus 16 bytes of tags, rounded up to 16. Which block does each one take under [first fit](#def-b3-garbage-collection-allocator), and under [best fit](#def-b3-garbage-collection-allocator)?

**Solution of Exercise 9.1.**

The requests need blocks of 64, 48, 160 and 96 bytes. [First fit](#def-b3-garbage-collection-allocator): 64 from the block of 96, which is split into 64 and a free 32; 48 in the block of 48; 160 in the block of 160; and 96 finds only the free 32, the 64 and the large block, so it cuts into the large block. [Best fit](#def-b3-garbage-collection-allocator): 64 in the block of 64, 48 in the 48, 160 in the 160, and 96 in the block of 96, every one an exact fit. [Best fit](#def-b3-garbage-collection-allocator) leaves the large block whole; [first fit](#def-b3-garbage-collection-allocator) leaves a sliver of 32 bytes and a hole of 64 (`arena_test.c` checks the four offsets of each policy).

**Exercise 9.2 ★.**

After `a = O(); b = a; c = [a, b]; d = {'k': a}; del a; b = None; c.append(c[0]); d['k'] = None`, what is the [reference count](#def-b3-garbage-collection-refcount) of the object, and what does `sys.getrefcount(c[0])` print?

**Solution of Exercise 9.2.**

Three: the list `c` holds it three times, and the names `a`, `b` and the dictionary no longer refer to it. `sys.getrefcount` prints 4, one more for its own argument.

**Exercise 9.3 ★.**

Roots: $r_1 \to A$ and $r_2 \to D$. References: $A \to B$, $B \to C$, $C \to A$, $E \to F$, $F \to E$, $G \to D$. Which objects are [garbage](#def-b3-garbage-collection-reachability)? Which of them does [reference counting](#def-b3-garbage-collection-refcount) free?

**Solution of Exercise 9.3.**

A, B and C are [reachable](#def-b3-garbage-collection-reachability) from $r_1$, and D from $r_2$. E, F and G are [garbage](#def-b3-garbage-collection-reachability). [Reference counting](#def-b3-garbage-collection-refcount) frees G, whose count is 0 (D’s count then falls from 2 to 1, and D stays). E and F keep each other’s count at 1 and are never freed.

**Exercise 9.4 ★.**

In [Listing 9.8](#lst-b3-garbage-collection-rc), the line that makes Ann Bob’s friend becomes `*bob.sponsor.borrow_mut() = Rc::downgrade(&ann);`. Predict the first block of the output.

**Solution of Exercise 9.4.**

`strong cycle:`, `counts 1 2`, `drop Ann`, `drop Bob`, then the line that now lies, `(end of scope: nothing dropped)`. Ann’s only strong reference is the local `ann`; Bob has two, the local and Ann’s `friend`. When the scope ends, both locals go: whichever goes first, Ann’s count reaches 0, Ann is dropped, and dropping her `friend` field removes Bob’s last count.

**Exercise 9.5 ★★.**

`exercises/ex5_sweep_bug.c` is `marksweep.c` with one line missing. On the workload of [Output 9.3](#out-b3-garbage-collection-ms) it marks fewer and fewer cells, sweeps fewer and fewer, and runs out of memory during request 367. Find the line, and explain the run.

**Solution of Exercise 9.5.**

The missing line is `heap[c].meta = WHITE;` in `sweep`: marked cells keep their marks. At the next collection, the first loop of `mark` skips every root already marked, and the stack never reaches past a marked cell, so only the cells allocated since are examined, and the marked count falls at each collection. Sweep frees only white cells, so every cell that was live at some collection stays allocated forever, even after it dies: a leak that grows at each collection, the swept count falls with it, and the heap is full during request 367, after 17 collections (`sweep_bug_test.c`). The bug can do worse: a new white cell [reachable](#def-b3-garbage-collection-reachability) only through an old marked one is never marked, and the sweep frees a cell the program still uses.

**Exercise 9.6 ★★.**

Write next fit: a placement policy for `arena.c` that starts each search at the block where the previous one stopped, wrapping round at the end. Why can its saved position become wrong after an `arena_free`, and how do you keep it right?

**Solution of Exercise 9.6.**

`exercises/ex6_next_fit.c` keeps the block where the last search succeeded, starts there, and wraps round at the epilogue. Freeing can merge the block at that position into the free block before it, or merge it into the freed block as its successor; the position then points into the middle of a block, where the walk would read payload as tags. `next_fit_free` moves it to the start of the merged block before freeing. `nextfit_test.c` checks after each of 20,000 random operations that the position is the start of a block, and that a request after a free goes on past the last block used instead of reusing the freed one.

**Exercise 9.7 ★★.**

Using the [tri-colour invariant](#def-b3-garbage-collection-marksweep), prove that after `mark` and `sweep` the [free list](#def-b3-garbage-collection-allocator) holds exactly the cells that were [garbage](#def-b3-garbage-collection-reachability) or free before, and that every cell is white again.

**Solution of Exercise 9.7.**

By [Theorem 9.6](#thm-b3-garbage-collection-tricolour), after `mark` the marked cells are exactly the [reachable](#def-b3-garbage-collection-reachability) ones; free cells are never marked, since no reference to them exists. `sweep` visits every cell once: a marked cell becomes white, a white one (allocated, not [reachable](#def-b3-garbage-collection-reachability): [garbage](#def-b3-garbage-collection-reachability)) is pushed on the [free list](#def-b3-garbage-collection-allocator), and a free one is left on the [free list](#def-b3-garbage-collection-allocator) where it already is. So the [free list](#def-b3-garbage-collection-allocator) ends with the free cells and the [garbage](#def-b3-garbage-collection-reachability), and no cell is marked.

**Exercise 9.8 ★★.**

The heap holds cells D, C, B, A, E, allocated in that order, with $A \to B, C$; $B \to D, A$; $C \to D$; $E \to A$. Only A is a root. List the cells Cheney’s algorithm copies, in order, with the new value of every reference.

**Solution of Exercise 9.8.**

A is copied to cell 0. Scanning A forwards B (copied to 1) and C (copied to 2). Scanning B forwards D (copied to 3) and A, which already has a [forwarding pointer](#def-b3-garbage-collection-copying), to 0. Scanning C forwards D to 3; scanning D finds nothing. Four cells are copied, A, B, C, D in that order, and the references become $0 \to 1, 2$; $1 \to 3, 0$; $2 \to 3$. E is never examined (`cheney_test.c`).

**Exercise 9.9 ★★.**

Find a short sequence of requests on an arena with two free blocks of 2,000 and 1,504 bytes, in that order, that [first fit](#def-b3-garbage-collection-allocator) serves entirely and [best fit](#def-b3-garbage-collection-allocator) does not.

**Solution of Exercise 9.9.**

Requests for blocks of 1,408, 1,504 and 592 bytes. [First fit](#def-b3-garbage-collection-allocator) takes 1,408 from the block of 2,000, leaving 592, puts 1,504 in the block of 1,504 and 592 in what was left: all served. [Best fit](#def-b3-garbage-collection-allocator) puts 1,408 in the smaller block, 1,504, leaving 96 bytes nobody can use; 1,504 then goes in the 2,000, leaving 496; the request of 592 is refused, with 592 bytes free in two pieces (`arena_test.c`).

**Exercise 9.10 ★★★.**

A program keeps exactly $L$ cells live and allocates without end, in a copying heap of $H$ cells with $H/2 > L$. Prove that in the steady state the collector copies $L/(H/2 - L)$ cells per cell allocated. What is the analogous cost of [mark and sweep](#def-b3-garbage-collection-marksweep), counting one unit per cell marked and one per cell swept?

**Solution of Exercise 9.10.**

After a collection from-space holds exactly the $L$ live cells, copied together, so $H/2 - L$ cells are free and the program allocates that many before the next collection. That collection copies the $L$ cells live then, by [Theorem 9.8](#thm-b3-garbage-collection-cheney), and the cycle repeats. Per cell allocated: $L/(H/2 - L)$. For [mark and sweep](#def-b3-garbage-collection-marksweep), after a collection the $H - L$ cells not live are free, the next collection comes after $H - L$ allocations, and it marks $L$ cells and sweeps $H$: $(L + H)/(H - L)$ units per cell allocated.

**Exercise 9.11 ★★★.**

Write `gc_write(c, k, v)` for `gen.c`, a store of the reference $v$ into field $k$ of cell $c$ with a [write barrier](#def-b3-garbage-collection-generational). Test that an old cell that receives a reference to a young one keeps it alive across a minor collection, and that without the barrier the young cell is lost.

**Solution of Exercise 9.11.**

`exercises/ex11_barrier.c`: if the cell written into is old, the value is a young cell, and the old cell is not yet in the set, it is added; then the store is done. `gen.c`’s minor collection already forwards the references of the remembered cells first, and empties the set. `gen_test.c` promotes a cell, stores into it a reference to a new young cell, then allocates past the nursery: with the barrier the young cell is promoted and the reference still finds its value 42; without it the minor collection does not see the reference, the young cell is not copied, and the reference points into a nursery that has been reused.

**Exercise 9.12 ★★★.**

Prove that [reference counting](#def-b3-garbage-collection-refcount) frees exactly the [garbage](#def-b3-garbage-collection-reachability) objects that cannot be reached from a cycle of [garbage](#def-b3-garbage-collection-reachability) objects.

**Solution of Exercise 9.12.**

The count of an object is the number of references to it from roots and from objects not yet freed. A [reachable object](#def-b3-garbage-collection-reachability) never refers to [garbage](#def-b3-garbage-collection-reachability), otherwise the [garbage](#def-b3-garbage-collection-reachability) would be [reachable](#def-b3-garbage-collection-reachability); so the count of a [garbage](#def-b3-garbage-collection-reachability) object counts only references from other [garbage](#def-b3-garbage-collection-reachability) objects.

Let $x$ be [garbage](#def-b3-garbage-collection-reachability) and not [reachable](#def-b3-garbage-collection-reachability) from any [garbage](#def-b3-garbage-collection-reachability) cycle. The [garbage](#def-b3-garbage-collection-reachability) objects from which $x$ can be reached form a finite graph with no cycle, otherwise $x$ would be [reachable](#def-b3-garbage-collection-reachability) from that cycle. By induction on the length of the longest path to $x$ in it: if there is none, $x$’s count is 0 and $x$ is freed; otherwise all the objects that refer to $x$ are freed, by induction, each decrementing $x$’s count, which reaches 0, and $x$ is freed.

Conversely, suppose an object on a [garbage](#def-b3-garbage-collection-reachability) cycle, or [reachable](#def-b3-garbage-collection-reachability) from one, is freed, and take the first such object to be freed. If it is on the cycle, its predecessor on the cycle is not yet freed and refers to it; otherwise the object before it on a path from the cycle is not yet freed and refers to it. Either way its count is at least 1 when it is freed, which is impossible. [Reachable objects](#def-b3-garbage-collection-reachability) are never freed for the same reason: the root or object before them on a path keeps their count at least 1.

## 9.7 Weekend problem

**Problem 9.1.**

Weekend problem — Choosing the heap size of the town’s server

The town’s server keeps the sessions of its last 500 requests, 4 cells each; every request also builds 12 cells of work that die with it ([Listing 9.9](#lst-b3-garbage-collection-server)). How much memory should it get? [Output 9.7](#out-b3-garbage-collection-pbcopy) runs 20,000 requests under the [copying collector](#def-b3-garbage-collection-copying) for heaps of $H$ cells from 2.5 to 16 times the live data $L$; [Output 9.8](#out-b3-garbage-collection-pbms) does the same under [mark and sweep](#def-b3-garbage-collection-marksweep).

```cpp
{
    nroots = keep + 1;
    for (int r = 0; r <= keep; r++) roots[r] = NIL;
}

static int serve(int r, int keep, int sess, int temp, int cyclic)  /* request number r */
{
    if (!build(keep, temp, r, 0) || !build(keep, sess, r, cyclic)) return 0;
    roots[r % keep] = roots[keep];
    roots[keep] = NIL;
    return 1;
}
```

***Listing 9.9.** One request of the server: work, then a session that replaces the oldest one. code/bachelor-3/09-garbage-collection/listings/server.h*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o pb_copying pb_copying.c cheney.c -lm && ./pb_copying 2.5 3 4 6 8 12 16
L = 2000 live cells, 20000 requests of 16 cells
  H/L      H collections    copied  copied/alloc    model
  2.5   5000         634   1267304         3.960    3.989
  3.0   6000         318    636320         1.988    2.003
  4.0   8000         158    314756         0.984    0.992
  6.0  12000          79    157504         0.492    0.498
  8.0  16000          52    104000         0.325    0.333
 12.0  24000          31     62000         0.194    0.200
 16.0  32000          22     44000         0.138    0.143
```

***Output 9.7.** The [copying collector](#def-b3-garbage-collection-copying): collections, cells copied, cells copied per cell allocated, and the model $L/(H/2 - L)$ with $L$ the mean number of cells copied by a collection.*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o pb_marksweep pb_marksweep.c marksweep.c -lm && ./pb_marksweep 1.25 1.5 2 3 4 6 8 16
  H/L      H collections    marked     swept  work/alloc    model
 1.25   2500         634   1267304    317696       8.913    8.978
 1.50   3000         318    636320    317680       4.970    5.006
 2.00   4000         158    314756    317244       2.959    2.984
 3.00   6000          79    157504    316496       1.973    1.995
 4.00   8000          52    104000    312000       1.625    1.667
 6.00  12000          31     62000    310000       1.356    1.400
 8.00  16000          22     44000    308000       1.238    1.286
16.00  32000          10     20000    300000       1.062    1.133
```

***Output 9.8.** [Mark and sweep](#def-b3-garbage-collection-marksweep) on the same requests: cells marked and swept, the work per cell allocated (marked plus the heap swept at each collection), and the model $(L + H)/(H - L)$.*

**Part I — Live data and allocation.**

1. How many cells are live once 500 requests have run, and how many more at most while a request is in progress?
2. How many cells does one request allocate, and what fraction of them are [garbage](#def-b3-garbage-collection-reachability) by the end of the next request?
3. With cells of 16 bytes, how many bytes are live? How many bytes does the server allocate over the 20,000 requests?
4. Why is the number of cells copied at a collection close to $L$ but not always equal to it?
5. The generational hypothesis: what fraction of the cells die before 16 more cells are allocated? And before 8,000?
6. Why must the work list being built be a root?

**Part II — The copying model.**

7. After a collection, how many cells can the program allocate before the next one?
8. Derive the cost $L/(H/2 - L)$ cells copied per cell allocated.
9. What happens to the cost as $H$ approaches $2L$ ? What is the smallest heap that works at all?
10. Show that for $H$ much larger than $L$ the cost is close to $2L/H$ , so that doubling the heap halves it.
11. With $L = 2{,}000$ , what heap gives one cell copied per cell allocated?
12. The memory the program never uses is a cost too. What fraction of a copying heap holds live data at $H = 4L$ ?

**Part III — Measured.**

13. Check the model against the measured column for $H = 2.5L$ and $H = 8L$ .
14. Why is the measured value slightly below the model for large $H$ ? (Look at the number of collections.)
15. How many collections would $H = 32L$ need, by the model?
16. From $H = 4L$ to $H = 8L$ , by what factor does the work fall? From $8L$ to $16L$ ?
17. The total number of copies at $H = 16L$ is exactly 22 times 2,000. Explain.
18. If copying a cell costs 20 ns, how much time does the collector spend at $H = 2.5L$ and at $H = 6L$ over the 20,000 requests?

**Part IV — Mark and sweep compared.**

19. Derive the model $(L + H)/(H - L)$ for [mark and sweep](#def-b3-garbage-collection-marksweep) .
20. Compare the two collectors with the same memory, $H = 4L$ : which does less work per cell, counting a copy and a sweep step alike?
21. Why does the [mark-and-sweep](#def-b3-garbage-collection-marksweep) cost never fall below 1, however large the heap?
22. A sweep step is cheaper than a copy: it reads one cell and may link it into the [free list](#def-b3-garbage-collection-allocator) . If a sweep step costs a quarter of a copy, which collector wins at $H = 4L$ , and at $H = 16L$ ?
23. What does the [copying collector](#def-b3-garbage-collection-copying) give in exchange for its idle half, besides speed?
24. Sum up: what heap size do you give the server, and why?

**Solution of Problem 9.1.**

**1.** $500 \times 4 = 2{,}000$ cells, so $L = 2{,}000$. While a request runs, at most 12 more: the work list as it is built; by the time the new session is built, the work list is already [garbage](#def-b3-garbage-collection-reachability), and the 4 session cells replace the work list’s.

**2.** $12 + 4 = 16$ cells; the 12 cells of work, 75 %, are [garbage](#def-b3-garbage-collection-reachability) once the request ends.

**3.** $2{,}000 \times 16 = 32{,}000$ bytes live; $20{,}000 \times 16 = 320{,}000$ cells allocated, $5{,}120{,}000$ bytes.

**4.** A collection may come in the middle of a request, when up to 12 more cells are live, and during the first 500 requests fewer than 500 sessions exist.

**5.** 75 % die within the 16 allocations of their own request; the other 25 % after 500 requests, about 8,000 allocations. The hypothesis holds for three cells out of four.

**6.** Every allocation may collect. A reference held only in a C variable would not be seen by the collector: the list’s cells would be [garbage](#def-b3-garbage-collection-reachability) to it, freed or, under copying, left behind while the variable still points at the old place.

**7.** $H/2 - L$.

**8.** Each collection copies $L$ cells and is followed by $H/2 - L$ allocations: $L/(H/2 - L)$ per cell allocated (exercise [9.10](#exo-b3-garbage-collection-10)).

**9.** It grows without bound: each collection frees almost nothing. Half the heap must hold the live data and a request in progress, $2{,}012$ cells, so $H \ge 2 \times 2{,}012 = 4{,}024$ at the very least.

**10.** $L/(H/2 - L) = 2L/(H - 2L)$, which is close to $2L/H$ when $H$ is much larger than $2L$; that is halved when $H$ doubles.

**11.** $L/(H/2 - L) = 1$ gives $H = 4L = 8{,}000$ cells, 128 KB; the measurement gives 0.984.

**12.** A quarter: half of the heap is to-space, empty, and from-space is half live data just after a collection.

**13.** At $2.5L$: 3.960 measured, 3.989 by the model; at $8L$: 0.325 and 0.333. Both within 3 %.

**14.** The cells allocated after the last collection are counted in the allocations but have not paid for a collection yet. At $16L$: 22 collections pay for $22 \times 14{,}000 = 308{,}000$ allocations, and 12,000 more are free riders. The larger the heap, the larger that last partial cycle, relative to the run.

**15.** $H/2 - L = 30{,}000$, so a collection every 30,000 allocations after the first, which comes at 32,000: 10 collections in 320,000 allocations.

**16.** $0.984/0.325 \approx 3.0$, then $0.325/0.138 \approx 2.4$: a doubling divides the work by more than 2, and the factor tends to 2 as $H$ grows.

**17.** A collection comes when from-space is full: the first after 16,000 allocations, which is 1,000 requests, the next every $16{,}000 - 2{,}000 = 14{,}000$ allocations, which is 875 requests. Every collection falls exactly between two requests, when exactly 2,000 cells are live.

**18.** $1{,}267{,}304 \times 20$ ns $\approx 25$ ms at $2.5L$; $157{,}504 \times 20$ ns $\approx 3.2$ ms at $6L$.

**19.** After a collection, the $H - L$ cells not live are free; the program allocates them; the next collection marks $L$ and sweeps $H$. Per cell allocated, $(L + H)/(H - L)$.

**20.** Copying: 0.984 copies per cell allocated; [mark and sweep](#def-b3-garbage-collection-marksweep): 1.625 units (model $5/3$). Counted alike, copying does less work, because it never visits the [garbage](#def-b3-garbage-collection-reachability).

**21.** The sweep visits every cell of the heap, and each collection frees at most $H - L$ of them: at least $H/(H - L) > 1$ sweep steps per cell allocated.

**22.** With a sweep step at a quarter of a copy and a mark at a copy, [mark and sweep](#def-b3-garbage-collection-marksweep) costs $(L + H/4)/(H - L)$: at $4L$, $2L/3L = 0.67$, less than copying’s 1; at $16L$, $5L/15L = 0.33$, more than copying’s $L/7L = 0.14$. [Mark and sweep](#def-b3-garbage-collection-marksweep) wins on a tight heap, copying on a large one.

**23.** Compaction: the live cells end up together and the free memory is one block, so allocation is a pointer increment and there is no [external fragmentation](#def-b3-garbage-collection-fragmentation); the copies also sit near each other in breadth-first order.

**24.** With copying, the work per cell allocated is $L/(H/2 - L)$, measured within 3 %; it is 1 at $4L$, and each doubling of the heap beyond that divides it by 3, then by 2.4, then by nearly 2. $8L$ = 16,000 cells (256 KB) costs one copy for every three cells allocated, about 2 ms of collection for 20,000 requests at 20 ns a copy; going to $16L$ saves about 1.2 ms more for twice the memory. For a server with this much live data, $6L$ to $8L$ is the sensible choice; below $4L$ the collector’s work grows quickly.
