11/34
Part 3 of 7 · MergingLearn and do
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.
012345678910
neither
BBBB
(4, 8) goes in as a new run.
before
BBBB
(1, 4) grows to (1, 8).
after
BBBB
(8, 10) grows to (4, 10).
both
BBBB
(0, 4) and (8, 11) make (0, 11).
a used unitthe block being freeda free unit
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.