6/34
Part 2 of 7 · The free listLearn and do

Keep the free space as sorted runs, and take the lowest run that fits

Here is that picture: only the free space, as runs.

A free list holds the free runs, sorted by start, with no two touching

The free runs
0123456789
memory
AAACC
The free list is [(3, 7), (9, 10)], and the blocks are {0: 3, 7: 9}, start to end.

This is the arena from the first figure, after free(3). Store what's free, not every unit. The free space is a set of runs, stretches of free units in a row.

Each run is half-open: (start, end) holds units start to end - 1. In the figure, (3, 7) stops just before unit 7. Addresses are offsets, so two back-to-back runs then share a number: (0, 4) and (4, 9) touch.

The free list keeps the runs in one Python list, with three rules:

  1. sorted by start
  2. no two overlap
  3. no two touch. A run never ends where the next one starts, because two such runs are really one. Freeing merges them.

A new arena of 20 units is [(0, 20)]. The live blocks go in a dict from start to end, so free can find a block's size from its address.

Memory now grows with the number of runs, k, and of blocks, not with the arena. A list of 1,000 runs held 128,024 bytes, about 128 bytes a run. That's the same for an arena of 10,000 units or 80 GiB.

is_free_list(free, size) checks a free list against the three rules above, plus the arena's bounds. Write it, so the figure's [(3, 7), (9, 10)] passes and two runs that touch fail.