3/34
Part 1 of 7 · alloc and freeLearn and do

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.

After alloc(4) and alloc(4) on an arena of 10 units
0123456789
memory
AAAABBBB
CallWhyResult
free(1)1 is inside A, not a block's startbad
free(8)8 is a free unitbad
free(10)10 is past the end of the arenabad
free(0)0 is A's start: it frees 4 unitsok
free(0) againA is free already: a double freebad

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 programExitstill running printed
frees p twicereturn code -6, the signal SIGABRTno
frees p + 160yes

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.