216 5. Engine Support Systems
appropriate size is marked as “in use,” and the remainder of the heap remains
free. When a block is freed, it is marked as such, and adjacent free blocks are
merged into a single, larger free block. Over time, as allocations and dealloca-
tions of various sizes occur in random order, the heap memory begins to look
like a patchwork of free and used blocks. We can think of the free regions as
“holes” in the fabric of used memory. When the number of holes becomes
large, and/or the holes are all relatively small, we say the memory has become
fragmented. This is illustrated in Figure 5.3.
The problem with memory fragmentation is that allocations may fail
even when there are enough free bytes to satisfy the request. The crux of the
problem is that allocated memory blocks must always be contiguous. For ex-
ample, in order to satisfy a request of 128 kB, there must exist a free “hole”
that is 128 kB or larger. If there are 2 holes, each of which is 64 kB in size, then
enough bytes are available but the allocation fails because they are not contigu-
ous bytes.
free
After one allocation...
After eight allocations...
After eight allocations and three frees...
After n allocations and m frees...
used free
Figure 5.3. Memory fragmentation.