Design a memory allocator: free lists and intervals
- Say what an allocator promises and its two failures: no run big enough while enough units are free in total, and a free of an address it never handed out
- Explain why one slot per unit costs O(size) per call and as much memory as the arena, with measured numbers
- Keep the free space as sorted half-open runs, take a block by first fit, and split the run it came from
- Free a block with one binary search, merge it with the runs on both sides, and show what skipping the merge does
- Track blocks and owners in dicts, release everything an owner holds, and raise on a double free or an address never handed out
- Answer the follow-ups with numbers: best fit against first fit, alignment, growing in place, why malloc can't compact, threads, and headers inside the memory
Memory allocator
Design Memory Allocator, LeetCode 2502, is on OpenAI's LeetCode company tag lists, the all-time, three-month and six-month ones (3 sources). Three OpenAI candidates report it under the name malloc, one as the only question, with some tests provided (3 reports). It starts like this:
Build
Allocator(size)for an arena ofsizeunits, at addresses 0 tosize - 1. A block is a run of units in a row, known by its start address. Asizebelow 1 raisesValueError.
alloc(n)hands out a block ofnunits and returns its start: the lowest address wherenfree units in a row begin. When no such run exists, it returnsNoneand changes nothing, even if enough units are free in total. Annbelow 1 raisesValueError.free(addr)frees the live block that starts ataddrand returns the number of units it held. Any other address raisesValueErrorand changes nothing: one inside a block, a free one, one outside the arena, and the start of a block that was freed already.
Call on Allocator(10)Returns alloc(3)0alloc(4)3alloc(2)7alloc(2)None, because only unit 9 is freefree(3)4, the size of the block at 3free(3)raises ValueError: that block is free alreadyalloc(2)3free(8)raises ValueError: 8 is inside the block at 7
Level 2 gives each block an owner, adds release(owner) and free_runs(), and makes the arena 80 GiB, too big for one slot per unit. Level 3 adds aligned blocks and resize, which grows a block in place or reports that it can't.
You don't write it yet. The lesson builds the pieces first: a free list of runs, first fit, the merge on free, and the dicts that track blocks and their owners. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.
This lesson builds on intervals: the free memory is a sorted list of runs, and freeing a block merges it with its neighbors the way the intervals lesson merges ranges.
An allocator hands out runs of memory and takes them back
Start with what an allocator does, on an arena small enough to draw.
An arena of 10 units. alloc(3), alloc(4) and alloc(2) all succeed. Then alloc(2) again: what comes back?
An arena of 7: A holds units 0 to 2, B unit 3, C units 4 to 6. Free A and C. Can alloc(4) succeed?
In C a bad free is undefined, so this allocator raises ValueError
Some calls to free are mistakes. Decide what the allocator does with them before you write it.
| Call | Why | Result |
|---|---|---|
free(1) | 1 is inside A, not a block's start | bad |
free(8) | 8 is a free unit | bad |
free(10) | 10 is past the end of the arena | bad |
free(0) | 0 is A's start: it frees 4 units | ok |
free(0) again | A is free already: a double free | bad |
Every bad call here is a bug in the caller. The C library doesn't promise to catch them. POSIX is the standard that C libraries follow. Its page for free says that if the argument doesn't match a pointer the allocator returned, or the space was already freed, the behavior is undefined. It adds: "Any use of a pointer that refers to freed space results in undefined behavior."
Here's what undefined meant on the Mac these numbers come from, macOS 26 on Apple silicon with Python 3.12. The code calls the C library through ctypes. It ran in a child process started with subprocess.run([sys.executable, "-c", code]), so a crash took down only the child:
import ctypes
libc = ctypes.CDLL(None)
libc.malloc.restype = ctypes.c_void_p
libc.free.argtypes = [ctypes.c_void_p]
p = libc.malloc(64)
libc.free(p)
# the same block a second time
libc.free(p)
print("still running")
It also ran with libc.free(p + 16) in place of the two frees: an address 16 bytes inside a live block.
| The program | Exit | still running printed |
|---|---|---|
frees p twice | return code -6, the signal SIGABRT | no |
frees p + 16 | 0 | yes |
Both results repeated on three runs. The second is the worse one, because the bug is still there and nothing said so.
An allocator written in Python has no reason to be that quiet. Raise ValueError for every address that isn't the start of a live block, and change nothing.
classify(blocks, size, addr) sorts an address into the rows of the table above: a block's start, inside a block, a free unit, or outside the arena. Write it for A and B from the figure, {0: 4, 4: 4}, so you know which addresses free must refuse.
One slot per unit is correct, but its cost grows with the arena
The obvious version keeps one slot for every unit
The first idea copies the memory: a list with one slot per unit.
class SlotAllocator:
def __init__(self, size):
# None: free; else the start of the block that holds it
self.slots = [None] * size
# start -> size of each live block
self.sizes = {}
def alloc(self, n):
# free slots in a row, ending here
run = 0
for addr, slot in enumerate(self.slots):
run = run + 1 if slot is None else 0
if run == n:
start = addr - n + 1
self.slots[start:addr + 1] = [start] * n
self.sizes[start] = n
return start
return None
def free(self, addr):
if addr not in self.sizes:
raise ValueError(f"no live block starts at {addr}")
n = self.sizes.pop(addr)
self.slots[addr:addr + n] = [None] * n
return n
a = SlotAllocator(8)
print(a.alloc(3), a.alloc(2), a.alloc(4))
print(a.slots)
0 3 None
[0, 0, 0, 3, 3, None, None, None]
A slot holds None while its unit is free, and otherwise the start of the block that holds it. alloc counts free slots in a row until the count reaches n. free clears the block's slots. Here is the scan for the alloc(4) that failed:
A slot holds the start of the block that holds its unit, or None, drawn as a free unit.
It's correct, and for an arena of 10 units it's a fine answer. The cost is the problem.
slot_alloc(slots, n) is the alloc of SlotAllocator above, pulled out as a function, with one bug in it: on an empty arena it returns -1. Find the line and fix it.
A request that fits nowhere reads every slot, so alloc is O(S)
A request that fits nowhere scans every slot, so alloc is O(S) for an arena of S units. free clears one slot per unit of the block.
Measured on arenas of S units holding 100 live blocks, each followed by a free gap as long as itself, with a request one unit bigger than any gap, so it fits nowhere:
The slot scan took 0.27 ms on an arena of 10,000 units. About how long on 10,000,000?
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
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:
- sorted by
start - no two overlap
- 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.
First fit takes the lowest run with room, not the smallest
First fit walks the runs in order and stops at the first one with at least n units:
def first_fit(free, n):
for i, (start, end) in enumerate(free):
if end - start >= n:
return i
return None
Here it is on the free list above, then one more request under two rules.
The free list is [(3, 7), (9, 10)]. alloc(2) takes the front of (3, 7). Then alloc(1): what does first fit return, and what does best fit?
The block takes the front of its run, and the rest stays free in place
The block takes the front of the run it came from, and the rest of the run stays free. In the figure, alloc(2) turned (3, 7) into (5, 7). Three requests, starting from [(2, 4), (7, 15), (17, 20)]:
| Request | Runs before | Run chosen | Block gets units | Runs after |
|---|---|---|---|---|
| 3 | [(2, 4), (7, 15), (17, 20)] | (7, 15) | 7 to 9 | [(2, 4), (10, 15), (17, 20)] |
| 2 | [(2, 4), (10, 15), (17, 20)] | (2, 4) | 2 to 3 | [(10, 15), (17, 20)] |
| 6 | [(10, 15), (17, 20)] | none | unchanged, and alloc returns None |
- The first row skips
(2, 4), which holds 2 units. - The second uses
(2, 4)up exactly, so it leaves the list. An empty(4, 4)left behind would hold nothing, and it would get in the way. Freeing the used units 4 to 6 later would put(4, 7)right next to it instead of merging with anything. - The third has 8 units free in total and no run of 6: the first failure again.
Taking the front is what makes first fit hand out the lowest address. It also keeps the list sorted without moving anything: the leftover (start + n, end) sits exactly where the old run did.
First fit is O(k) for k runs, whatever the arena's size
Walking to the last of k runs, best of 5:
First fit walked to the last of 1,000 runs in 0.027 ms. About how long for 10,000 runs?
Free a block, and merge it with the free runs on each side
Handing memory out is half the job. Now take it back.
Freed runs that never merge break the arena into pieces
free puts the block's units back as a run. Putting it back in order isn't enough. Allocate three blocks of 4 in an arena of 12 and free all three. Put each back with insort, which inserts into a sorted list, and the free list is [(0, 4), (4, 8), (8, 12)]. The whole arena is free, and a request for 12 returns None, because no single run holds 12.
Over a longer run it gets much worse. Here's a workload on an arena of 10,000 units with the take you just wrote. It runs 20,000 steps. Each step allocates a random 1 to 100 units while fewer than 60% of the units are in use, and otherwise frees a random live block. random.Random(1) draws the sizes.
20,000 random steps on an arena of 10,000 units, with freed runs never merged. About what share of requests failed?
A freed block can touch only two runs: the one just before it and the one just after
Walking every run on each free is more work than a free needs.
Before the call, no two runs touched, and every unit of the block was in use. So the freed block (start, end) can touch at most two runs:
- the run that ends exactly at
start, which is just before it in the list - the run that starts exactly at
end, just after it.
That gives the four cases in the figure. In the last one, the run before, the block and the run after become one run, and the list gets one shorter.
The manual for glibc, the GNU C library that Linux programs use, says neighbouring chunks of any size can be merged on a free: "Neighboring chunks can be coalesced on a free no matter what their size is."
touches(free, start, end) names the case from the figure for a block being freed. Write it to return 'neither', 'before', 'after' or 'both'. A scan of the list is fine here.
One binary search finds both neighbours
The free list is sorted by start, so you don't have to walk it to find the neighbors.
The free list is [(0, 4), (8, 12), (20, 30)], and the block (4, 8) is freed. bisect finds position i = 1. Which runs can it touch?
Record each live block, so free knows its size and refuses bad addresses
A dict from start to end gives the size and catches every bad free
The free list knows what's free. The allocator also needs to know what it handed out. free(addr) gets only an address, so it has to find the block's size, and it has to refuse an address it never handed out. A dict from each live block's start to its end does both:
def free(self, addr):
if addr not in self.blocks:
raise ValueError(f"no live block starts at {addr}")
end = self.blocks.pop(addr)
give_back(self.free_list, addr, end)
return end - addr
The check is exact and O(1). Take the bad frees from the table near the top of the lesson:
- A second free of the same block finds nothing, because the first one popped the key.
- An address inside a block isn't a key.
- Neither is a free unit, or one past the end of the arena.
And because the check comes first, a bad call changes nothing.
free(blocks, addr) takes blocks, the dict from each live block's start to its end, and it has a bug: given address 1, it frees the block at 0. Fix it with the dict check above.
Owners need a second dict, from each owner to the starts it holds
The practice problem also frees every block one owner holds, in a single call. That needs a second dict.
P and R belong to job-1, and Q to job-2.
| State | Value |
|---|---|
blocks | {0: (3, "job-1"), 3: (5, "job-2"), 5: (8, "job-1")} |
owned | {"job-1": {0, 5}, "job-2": {3}} |
| free list | [(8, 10)] |
after free(5), which returns 3 | owned is {"job-1": {0}, "job-2": {3}} |
then release("job-1"), which returns 3 | it frees only the block at 0 |
The practice problem gives each block an owner, such as the job that asked for it. It adds release(owner), which frees everything that owner holds, the way a job's memory goes back when the job ends.
To find an owner's blocks without scanning them all, keep a second dict, owned, from each owner to the set of its blocks' starts. Store the owner next to the end: blocks[start] = (end, owner).
| State | Answers | Changes on alloc | Changes on free |
|---|---|---|---|
free_list | where the free runs are | split a run | merge with neighbours |
blocks, start to (end, owner) | is this a live block, how big, whose | add the start | remove the start |
owned, owner to a set of starts | which blocks an owner holds | add the start to its set | remove the start, and the owner once its set is empty |
The three must agree after every call. In the table, free(5) took 5 out of job-1's set, so the release that came after freed only the block at 0.
owned_from(blocks) builds the owned dict from the blocks dict in the table above. Write it, and leave out the blocks whose owner is None.
A free by address must leave the owner's set, and release must walk a copy
With two dicts, every call has to keep both of them right.
owned = {"job-1": {0, 5}}
for start in owned["job-1"]:
owned["job-1"].discard(start)
RuntimeError: Set changed size during iteration
That loop is release in small: it walks an owner's set while each free removes a start from it. Two details keep the three states agreeing.
First, free by address has to take the start out of its owner's set. Otherwise a later release frees that address again:
- If the address is still free, that
freeraisesValueErrorpartway through the release, and the blocks the walk hadn't reached stay live. - If it was handed out again since,
releasesilently frees the new block, which may belong to another owner.
Second, release must walk a copy. A set can't change size while a loop walks it. A release that looped over self.owned.get(owner, ()) and called free raised the same RuntimeError after the first free, with two blocks for the owner. Walk list(...) or sorted(...) of the set, and the loop is safe.
release costs one free per block the owner holds, each O(log k) to search plus the shift. A set rather than a list for each owner's starts makes the removal in free O(1).
The Allocator in the editor has take, give_back and alloc written, with owners. Finish its free so it keeps owned up to date, and write its release.
alloc(n, owner) records each block in self.blocks as start -> (end, owner), and in self.owned, a dict from each owner to the set of its blocks' starts. Finish free(addr): drop the block from its owner's set, and drop the owner once its set is empty, then give the run back and return the block's size. Then write release(owner): free every block owner holds and return the total units freed, 0 for an owner that holds nothing.
An aligned block starts at a multiple, and the units skipped to reach it stay free
Some requests need an aligned block, one that starts at a multiple of a number such as 16.
Round each run's start up, and the block fits if it still ends inside the run
align = 16
for start in (3, 16, 17):
print(start, -(-start // align) * align)
Round 3, 16 and 17 up to a multiple of 16. What do you get?
The units skipped to reach an aligned start stay free
Rounding up skips some units. Those units still belong on the free list.
The block starts at 16. The units skipped to reach it, (3, 16), stay free, and so does (32, 64).
On an arena of 64 units with a block at 0 to 2, the free list is [(3, 64)]. A request for 16 units aligned to 16 rounds 3 up to 16. The block is 16 to 31, and the free list becomes [(3, 16), (32, 64)].
Taking an aligned block out of the middle of a run can leave two pieces: the units skipped to reach at, and the tail after the block. Those 13 skipped units are still free, and the next alloc(13) returns 3.
Drop the gap and they're gone for good. No live block holds them, so nothing ever frees them, and they never reach the free list. That's a leak.
take_aligned(free, n, align) is take with alignment: it rounds each run's start up and keeps the gap before the block as a free run. Fill in the two marked lines in the editor.
Finish take_aligned(free, n, align), which works like take except that the block must start at a multiple of align, a power of two. In each run, round the start up to a multiple of align. The block fits if it still ends inside the run. Replace the run with the pieces left on each side of the block, leaving out empty ones. Addresses can be any size, so stay in integers.
For an align of 1 or more, align & (align - 1) is 0 exactly for powers of two
Alignments are powers of two, and one bit trick checks that in a line.
print(8 & 7, 12 & 11, 0 & -1)
What do 8 & 7 and 12 & 11 give?
A block grows in place only into the free run that starts where it ends
resize asks a block to grow or shrink without moving it.
Growing needs a free run that starts exactly at the block's end and reaches far enough
A ends at 4 and asks to end at 7. The free run that starts at 4 is (4, 6). Can A grow in place?
Shrinking always works, and the cut-off units merge like any free
Shrinking is the easy half of resize. Say n is the new, smaller size:
The units cut off the end are free now, and they may touch the run after them, so they go back through the same merge as any free. Here they joined (6, 10).
The block keeps its start, so the dict key doesn't change, and it keeps its owner. Growing or shrinking a block never touches owned.
shrink(blocks, free, addr, n) is the shrink half of resize, and give_back from the merging part sits above it in the editor. Write shrink, and the figure's block of 6 units becomes 2.
vLLM grows a request's cache by one same-size block at a time, from anywhere
Real systems often avoid growing in place altogether. vLLM is one example.
c0, c1 and c2 are one request's cache, and the block table maps them to blocks 7, 2 and 5. To grow, c3 takes any free block, such as 0. The block numbers are made up for the picture.
vLLM is a serving engine for large language models. It doesn't grow a request's cache of attention keys and values, the KV cache, in place at all.
It takes one contiguous chunk of GPU memory for caches and cuts it into blocks of one fixed size. Each request gets a block table that says where its first block sits, its second, and so on. A cache grows by one block from anywhere there's room, so it never needs the run right after it. And since all blocks are the same size, any free block fits.
Its paper: "Separating logical and physical KV blocks allows vLLM to dynamically grow the KV cache memory without reserving it for all positions in advance, which eliminates most memory waste in existing systems." The price is each request's last block, partly empty.
When an interviewer asks how a model server grows a cache, give this answer before growing in place. The KV cache lesson covers it as paged attention.
blocks_needed(tokens, block_size) and wasted(tokens, block_size) count the same-size blocks a request's cache fills, and the empty slots in its last block, the price vLLM pays. Write both.
One of vLLM's authors at Ray Summit 2023. The three kinds of wasted KV cache memory from 4:51, internal and external fragmentation among them, then PagedAttention from 6:16: fixed-size blocks, like an operating system's pages, so a request's cache needn't sit in one piece. That's the block-at-a-time growth in this part's last step.
A worked example: rebuild the free runs from a dump
Clarify first: blocks may touch, and an overlap or a block past the end is corrupt
The prompt: a server crashed, and its dump lists the live blocks of an arena of size units as (start, n) pairs, in no particular order. Return the free runs, half-open and in order. If the dump is corrupt, with two blocks that overlap or a block that runs past the arena, raise ValueError. Here size = 100:
DUMP = [(40, 10), (0, 15), (15, 5), (70, 30), (52, 8)]
print(sorted(DUMP))
[(0, 15), (15, 5), (40, 10), (52, 8), (70, 30)]
Size 100. Live blocks (0, 15), (15, 5), (40, 10), (52, 8), (70, 30), as (start, n). What are the free runs?
Sorted by start, every gap before a block is a free run
The obvious answer marks a slot for every unit of every block, then reads the runs off the slots. It's O(S) for an arena of S units, and a dump from the practice problem's 80 GiB arena makes that 85,899,345,920 slots. Say it and its cost, and move on.
The insight. This is free time from the intervals lesson, with one change. Sort the blocks by start and walk them with one number, free_from: every unit before it is in a block or already reported free.
- A block that starts after
free_fromleaves a gap, and that gap is a free run. - A block that starts before
free_fromoverlaps the one before it. In free time that was a meeting inside another meeting, handled withmax. Here it's corruption, and the answer is an error.
def free_runs_from_dump(size, blocks):
# every unit before free_from is used or reported
runs, free_from = [], 0
for start, n in sorted(blocks):
if n < 1 or start < free_from or start + n > size:
raise ValueError(f"block ({start}, {n}) is empty, overlaps the one before it, or runs past the end")
if start > free_from:
runs.append((free_from, start))
free_from = start + n
if free_from < size:
runs.append((free_from, size))
return runs
print(free_runs_from_dump(100, DUMP))
[(20, 40), (50, 52), (60, 70)]
Trace it the way you'd narrate it:
| Block | free_from before | Gap? | free_from after |
|---|---|---|---|
(0, 15) | 0 | no | 15 |
(15, 5) | 15 | no, it touches | 20 |
(40, 10) | 20 | (20, 40) | 50 |
(52, 8) | 50 | (50, 52) | 60 |
(70, 30) | 60 | (60, 70) | 100 |
free_from ended at 100, so there's no run at the end. No two of the runs touch, because a gap is reported only when a block starts after free_from, and two gaps always have a block between them.
largest_free(size, blocks) walks the dump the way free_runs_from_dump does, with free_from, but keeps only the longest gap. Write it for DUMP.
Test the edges, check against the slot version, then give the cost
The edges.
- Add
(45, 10)to the dump, and the walk reaches it withfree_fromat 50, so it raises. - Two blocks that both start at 0 raise on the second.
(90, 20)runs past 100,(5, 0)holds nothing and(-3, 5)starts before 0, and all three raise.[]gives[(0, 100)], and[(0, 100)]gives[].
The check start < free_from catches a negative start for free, because free_from begins at 0.
Test it against the slot version. On 2,000 random dumps of up to 10 blocks in arenas of up to 60 units, the two agreed every time.
Cost. The sort is O(b log b) for b blocks, and the walk is O(b). The arena's size never enters: 100,000 blocks scattered over an 80 GiB arena took 44.7 ms and gave 100,001 runs.
This is also the test you want for the practice problem. Rebuild the free runs from the allocator's own live blocks after every call, and compare them with its free list. If they ever differ, a merge, a split or a free went wrong on that exact call.
free_runs_from_dump from the worked example is in the editor, finished. Write agrees(size, blocks, free_list), the check to run after every call: rebuild the runs from the allocator's blocks and compare them with its free list.
What interviewers ask next
Once the levels pass, the follow-ups compare designs, starting with how to pick a run.
First fit or best fit: on one random workload, best fit failed about half as often
Best fit takes the smallest run that fits instead of the lowest. It can leave big runs whole for big requests, as in the first case. It can also leave slivers too small to use, as in the second. Neither rule wins on every sequence of requests, so the question is which wins more often.
Here are the two on one random workload:
- The arena has 100,000 units.
- The workload runs 40,000 steps.
- An allocation asks for
int(2 ** rng.uniform(0, 10))units: 1 to 1,023, with small sizes more likely. - A step allocates while fewer than 90% of the units are in use, and otherwise frees a random live block.
- Every request that failed had at least 10,000 units free in total, ten times the largest request, so every failure was fragmentation.
| Seed | First fit: failed | Best fit: failed | First fit: mean runs | Best fit: mean runs |
|---|---|---|---|---|
| 1 | 4,463 of 23,325 (19.13%) | 1,670 of 21,354 (7.82%) | 521 | 190 |
| 2 | 3,999 of 23,058 (17.34%) | 1,886 of 21,529 (8.76%) | 506 | 201 |
| 3 | 4,444 of 23,354 (19.03%) | 2,037 of 21,656 (9.41%) | 530 | 209 |
On this workload best fit failed about half as often and kept about 60% fewer runs. With the same workload held under 80% full, failures were rare for both: 15 to 20 per run for first fit and 4 to 7 for best fit, out of about 20,000 requests.
A random workload isn't a real program, so don't quote it as a law. The real-program evidence comes from a survey that Doug Lea cites in his article on dlmalloc, the allocator that glibc's manual says its own is derived from: "As shown by Wilson et al, best-fit schemes (of various kinds and approximations) tend to produce the least fragmentation on real loads compared to other general approaches such as first-fit."
The cost is the search. Best fit can't stop at the first run that fits, so on a plain list it walks all k runs every time.
first_fit and best_fit are in the editor, finished. Write failures(free, sizes, pick), which serves a list of requests with one of the two rules and counts the failures, and run it on the two figures above.
A length index makes best fit O(log k), and first fit needs a tree
On a plain list, best fit has to look at every run. A second index fixes that.
| Order | The three free runs |
|---|---|
| by start | (0, 50), (60, 64), (70, 72) |
| by length, as (length, start) | (2, 70), (4, 60), (50, 0) |
Best fit for 3: bisect_left(by_length, (3, 0)) is 1, so it takes (4, 60), the run of 4 that starts at 60.
free is a binary search plus a shift, 8.6 µs at 100,000 runs above. First fit is a walk, 2,936 µs. To speed up the walk, index the runs a second way.
Keep the free runs sorted by length as well, as (length, start) pairs, and best fit is one bisect_left for (n, 0). That's O(log k) to search, with two lists to keep in step on every call.
Lea's allocator groups free chunks into bins by size, and his article describes the small ones: "Bins for sizes less than 512 bytes each hold only exactly one size (spaced 8 bytes apart, simplifying enforcement of 8-byte alignment)."
First fit by address can be made O(log k) too. Use a balanced search tree keyed by start, in which each node also records the longest run below it, so the search knows which side has room. Python's standard library has no such tree. Name it, give its cost, and don't write it in 45 minutes.
best_by_length(by_length, n) searches the free runs kept as (length, start) pairs, as in the second row of the table above. Write it with one bisect_left.
A C allocator can't compact, because the program holds the addresses
Another follow-up: why not slide every live block down and end fragmentation for good?
A C program holds raw addresses, not handles, so nothing can update them after a move.
Moving every live block down to the start of the arena, compaction, would turn all the free space into one run. A C allocator can't do it, because the program holds the addresses. A pointer to a block can sit in any variable, struct or register, and the allocator can't find them all to update them. In the figure, a pointer that still holds 4 for B now points into C.
So a C allocator never moves a live block on its own. realloc moves one only when asked, and hands back the new address: "The value of realloc is the new address of the block." CPython makes the same promise about objects. id() is "guaranteed to be unique and constant for this object during its lifetime", and the same docs say that in CPython it's the address of the object in memory.
Compaction works when every reference goes through something the allocator controls. Give callers a handle, a block id, and keep a table from id to address. Then compaction slides each live block down, updates the table, and leaves one free run. It costs a copy of every live unit plus one table update per block. The program has to be stopped or locked out while it runs.
compact(table, size) compacts an arena whose callers hold handles: table maps each handle to (address, n), as in the figure. Write it to slide every block down in address order.
Threads calling at once can lose units, and one lock stops that
So far, one caller at a time. Here is what two threads can do to the free list.
The free list is [(10, 20)]. Thread 1 frees (0, 10) and thread 2 frees (20, 30) at the same time, with no lock. What can the free list end up as?
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.
The tests you'd write
- A model with one slot per unit, slow and obviously right, run side by side with the real allocator on a few hundred random calls in an arena of 64 units. Compare every return value and the free runs after every call. The practice problem's tests do exactly that.
- The worked example's rebuild after every call, as an invariant check.
- Then the edges by hand: a request of exactly the arena's size, and one unit too big. A freed block with a free run on each side, on one side and on neither. Two runs one used unit apart. A double free, and a free inside a block. An owner whose block was freed by its address. An aligned request whose run is too short after rounding. A grow that must fail and change nothing.
A call here is a method name and its argument, such as ("alloc", 4). getattr(obj, "alloc") looks up the method by its name, so getattr(obj, name)(arg) calls it. outcome(obj, call) and first_disagreement(calls, real, model) are the harness from the first bullet above, which runs an allocator beside a slot model like SlotAllocator. The tests bring both allocators, so the print line tries outcome on a plain list.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.An arena of 7 units has free runs
(0, 3)and(4, 7), half-open, with a live block at unit 3. What does first fit return for a request of 4 units?2.The free list is
[(0, 4), (8, 12)]and the block(4, 8)is freed. What should the free list be afterwards?3.An arena of S units holds k free runs. What does first fit cost per allocation with one slot per unit, and with a free list?
4.Why does a C allocator never move a live block to merge the free space into one run?
5.The free list is
[(3, 64)]. A request asks for 16 units aligned to 16. What doesallocreturn, and what is the free list afterwards?6.
release(owner)runsfor start in self.owned[owner]: self.free(start), andfreeremoves each start fromself.owned[owner]. What happens when the owner holds two blocks?
Practice
Sources (10)
- free: free allocated memory · POSIX.1-2024 (IEEE Std 1003.1-2024), The Open Group Base Specifications Issue 8 · Jun 14, 2024
“if the argument does not match a pointer earlier returned by aligned_alloc() ... or if the space has been deallocated by a call to free() ... the behavior is undefined”
- Allocating Aligned Memory Blocks · The GNU C Library Reference Manual, version 2.42 · Jul 28, 2025
“The address of a block returned by malloc or realloc in GNU systems is always a multiple of eight (or sixteen on 64-bit systems).”
- Changing the Size of a Block · The GNU C Library Reference Manual, version 2.42 · Jul 28, 2025
“Since the space after the end of the block may be in use, realloc may find it necessary to copy the block to a new address where more free space is available.”
- The GNU Allocator · The GNU C Library Reference Manual, version 2.42 · Jul 28, 2025
“Neighboring chunks can be coalesced on a free no matter what their size is.”
- Freeing Memory Allocated with malloc · The GNU C Library Reference Manual, version 2.42 · Jul 28, 2025
“Freeing a block alters the contents of the block.”
- A Memory Allocator · Doug Lea, State University of New York at Oswego · Apr 4, 2000
“Chunks of memory carry around with them size information fields both before and after the chunk.”
- Efficient Memory Management for Large Language Model Serving with PagedAttention · arXiv 2309.06180 · Sep 12, 2023
“Separating logical and physical KV blocks allows vLLM to dynamically grow the KV cache memory without reserving it for all positions in advance, which eliminates most memory waste in existing systems.”
- Memory Management: The pymalloc allocator · Python 3.12 documentation · Oct 26, 2026
“It uses memory mappings called “arenas” with a fixed size of either 256 KiB on 32-bit platforms or 1 MiB on 64-bit platforms.”
- Built-in Functions: id · Python 3.12 documentation · Oct 26, 2026
“This is an integer which is guaranteed to be unique and constant for this object during its lifetime.”
- bisect: insort_left · Python 3.12 documentation · Oct 26, 2026
“Keep in mind that the O(log n) search is dominated by the slow O(n) insertion step.”