14/34
Part 4 of 7 · Live blocks and ownersLearn and do
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.