31/34
Part 7 of 7 · Follow-upsLearn and do

Lea's allocator keeps its sizes and its free list inside the memory it manages

Your allocator keeps its records in Python dicts and lists. A C allocator has no such place to put them.

Field, in memory orderBelongs to
sizethe chunk below, free
next, prevthe chunk below: its place in the free list
size, at its endthe chunk below: read to find where it starts
size, just before pthe chunk being freed
data, which starts at pthe chunk being freed: the address free(p) gets
size, at its endthe chunk being freed

free(p) in C gets only an address. So the allocator writes each block's size in a small header just before the address it hands out, and free reads it back from there.

Lea's allocator writes the size at both ends, which his article calls boundary tags: "Chunks of memory carry around with them size information fields both before and after the chunk." With a size at the end of every chunk, a chunk being freed can read the size of the chunk just below it, step back to that chunk's start, and merge. That's O(1), with no sorted list to search.

The free list lives in the free chunks themselves. Each one holds the pointers to the next and previous free chunk, a doubly linked list, so a chunk unlinks in O(1) when it's merged or handed out. The glibc manual warns callers about exactly this: "Freeing a block alters the contents of the block."

A free chunk must hold its sizes and its pointers, which sets a minimum size. Lea's article gives it: "the smallest allocatable chunk is 16 bytes in systems with 32-bit pointers and 24 bytes in systems with 64-bit pointers." That article, last changed in 2000, says itself that it doesn't cover details of the current version. Use it for the ideas, not for the numbers of today's glibc.

A free list that lives inside the free chunks also explains why a double free is so dangerous in C:

A free list kept as a stack: free(X) sets X.next = head, then head = X
free(B)
head →
B
free(A)
head →
A
→
B
free(A) again
head →
A
→back to A itself
A.next is A: the walk goes A, A, A, ...

The second free of A sets A.next to A: a chunk that points at itself. That's a cycle, and a walk of the free list that expects an end never finds one. B is lost from the list too.

below(mem, start) and above(mem, start) find a chunk's neighbours from its boundary tags. mem is a toy memory of three chunks back to back, each with its size in its first and its last slot.