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.