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 order | Belongs to |
|---|---|
| size | the chunk below, free |
| next, prev | the chunk below: its place in the free list |
| size, at its end | the chunk below: read to find where it starts |
| size, just before p | the chunk being freed |
| data, which starts at p | the chunk being freed: the address free(p) gets |
| size, at its end | the 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:
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.