Section 4.9

Heap fragmentation

Definition

Heap fragmentation is the state in which the free memory of a heap is split into pieces, so that a request for one block can fail although the free pieces together hold enough bytes. The heap is the memory from which a program obtains blocks while it runs, through an allocator: the library code that hands blocks out and takes them back (in C, the functions malloc and free). A block must be one unbroken range of addresses, so the largest free piece, not the total, limits a request.

The idea

A small device has a heap of 1024 bytes. Over a day it allocates and frees blocks of different sizes, some kept for a moment and some kept for hours. At the end of the day the allocator reports 400 free bytes, yet a request for 300 bytes fails. The 400 free bytes are two pieces of 200 bytes each, and between them sits a small block that the program still uses. No single piece can hold 300 bytes, and the allocator cannot join the two pieces across the block in use.

A row of parking spaces along a street is a fair picture. Cars of different lengths arrive and leave at different times. After a while the empty stretches add up to the length of a bus, but they lie in gaps between parked cars, so the bus cannot park. The picture stops being accurate in one respect. A parked car could be asked to move up and close a gap. A block in a C program cannot be moved, because the program holds its address in pointers, and moving the block would leave every such pointer aimed at the old place.

How it works

An allocator that manages one fixed region of memory, often called an arena, works with these parts:

The allocator works in four steps.

  1. Allocate. For a request of nn bytes, the allocator rounds nn up to the alignment, adds the header, and searches the free list for a free block at least that large. First fit takes the first such block it finds; best fit takes the smallest one that is large enough.

  2. Split. If the chosen free block is larger than needed, the allocator cuts it in two, hands out the front part and keeps the rest as a smaller free block. If the rest would be too small to hold a header and some data, the allocator hands out the whole block instead.

  3. Free. When the program frees a block, the allocator marks the block free.

  4. Coalesce. If the block just freed borders another free block, the allocator joins (coalesces) the two into one larger free block. Coalescing is the only way free pieces grow. It works only between neighbors: a block in use that lies between two free blocks keeps them apart.

Two kinds of waste result. External fragmentation is free memory split into pieces that lie between blocks in use: the bytes are free, but no single piece is large enough for the request. Internal fragmentation is memory inside a handed-out block that the program did not ask for: the alignment rounding, a leftover too small to split off, and, in allocators that serve only certain sizes, the gap between the size requested and the size served. Heap fragmentation usually means external fragmentation, because that is the kind that makes a request fail while the total looks sufficient.

External fragmentation grows when blocks of mixed sizes have mixed lifetimes. A long-lived small block that was allocated between short-lived large ones stays in place after its neighbors are freed, and keeps the two gaps apart for as long as it lives. The pattern depends on the order of the requests, so two runs of the same program with different input can fragment the heap differently.

A fixed-size block allocator, often called a memory pool, avoids external fragmentation by giving up variable sizes. It divides a region into NN blocks of one size, chosen when the pool is created, and hands out whole blocks. Any free block fits any request no larger than the block size, so such a request fails only when all NN blocks are in use. The cost moves elsewhere. A request smaller than the block size wastes the difference inside the block, which is internal fragmentation. And the pool’s region serves only this pool: its free blocks cannot help a request for a larger size, even while the general heap is full. The Zephyr real-time operating system §6.33 offers such an allocator under the name memory slab (k_mem_slab).

Worked example

Take an arena of 1024 bytes. The allocator uses an 8-byte header and rounds every block to a multiple of 8 bytes. All block sizes below are whole blocks, header included, so a block of 200 bytes gives the program 200−8=192200 - 8 = 192 bytes. Starting from an empty arena, the program allocates four blocks in this order: A of 200 bytes, B of 104 bytes, C of 200 bytes and D of 520 bytes. Together they fill the arena: 200+104+200+520=1024200 + 104 + 200 + 520 = 1024 bytes. A and C hold short-lived data and are freed; B and D stay in use. The arena now reads, from its start: free 200, B in use 104, free 200, D in use 520.

The total free memory is 200+200=400200 + 200 = 400 bytes. The largest free block is 200 bytes, so the largest request the allocator can grant is 200−8=192200 - 8 = 192 bytes. A request for 300 bytes is rounded up to the next multiple of 8, which is 304, because 300/8=37.5300 / 8 = 37.5 and 38×8=30438 \times 8 = 304. With the header it needs a block of 304+8=312304 + 8 = 312 bytes. No free block holds 312 bytes, so the request fails, although 400 bytes are free.

Now the program frees B. B borders a free block on each side, so the allocator coalesces all three into one free block of 200+104+200=504200 + 104 + 200 = 504 bytes. The 312-byte block for the request now fits. The allocator splits the 504-byte block into the 312-byte block and a free block of 504−312=192504 - 312 = 192 bytes. Of the 312 bytes, 8 are header and 304−300=4304 - 300 = 4 are rounding, so 12 bytes are internal fragmentation. Before B was freed, 400 free bytes were already more than enough. What changed is that the free bytes became one piece.

For contrast, take a pool of 16 blocks of 64 bytes, with no header per block, which serves objects of 40 bytes. Its region is 16×64=102416 \times 64 = 1024 bytes. Whenever fewer than 16 objects are in use, the next request succeeds, whatever the order of earlier requests and frees: the pool has no external fragmentation. Each object wastes 64−40=2464 - 40 = 24 bytes, which is 24/64=37.5%24 / 64 = 37.5\% of every block in use, and no request larger than 64 bytes can use the pool at all.

Stated precisely

Let the free blocks of the heap have sizes f1,f2,…,fkf_1, f_2, \dots, f_k in bytes, header space included. The total free memory is F=f1+f2+…+fkF = f_1 + f_2 + \dots + f_k, and the largest free block fmaxf_{\max} is the largest of the fif_i. Let hh be the header size and aa the alignment, both in bytes, with hh a multiple of aa. A request for nn bytes needs a block of s(n)=h+a⌈n/a⌉s(n) = h + a \lceil n / a \rceil bytes, where ⌈x⌉\lceil x \rceil means xx rounded up to a whole number.

For an allocator that may use any free block that is large enough, as first fit and best fit do, a request for nn bytes succeeds if and only if s(n)≤fmaxs(n) \le f_{\max}. If fmax>hf_{\max} > h, the largest request that succeeds is nmax=a⌊(fmax−h)/a⌋,n_{\max} = a \lfloor (f_{\max} - h) / a \rfloor, where ⌊x⌋\lfloor x \rfloor means xx rounded down to a whole number. In the example, fmax=200f_{\max} = 200, h=8h = 8 and a=8a = 8, so nmax=8⌊192/8⌋=8×24=192n_{\max} = 8 \lfloor 192 / 8 \rfloor = 8 \times 24 = 192 bytes. A request fails because of fragmentation exactly when s(n)≤Fs(n) \le F but s(n)>fmaxs(n) > f_{\max}: enough bytes are free, but not in one piece.

A common summary of the state is the ratio 1−fmax/F1 - f_{\max} / F. It is 0 when all free memory is one block, and it approaches 1 as the free memory splits into many small pieces. In the example it is 1−200/400=0.51 - 200 / 400 = 0.5. The ratio describes the heap at one moment. It does not predict whether a later request will succeed.

The condition s(n)≤fmaxs(n) \le f_{\max} assumes an allocator that considers every free block. An allocator that sorts free blocks into size classes in order to answer in constant time, such as TLSF (two-level segregated fit), searches only the classes whose every block is large enough. It can therefore refuse a request although one free block is large enough, when that block lies in the same size class as the request.

Limits and common mistakes

Total free memory does not tell whether a request will succeed. Many heap statistics report only the total. A total that stays level over a long test shows that no memory leak §4.8 (memory that is never released) is growing, but the largest free block can still shrink. Track the largest free block, or the largest request the allocator can grant, next to the total.

Fragmentation grows late. It depends on the order and the lifetimes of requests, so a short test with tidy input can leave the heap in one piece while weeks of varied traffic split it. When requests vary in size and blocks cannot move, no allocator avoids fragmentation for every possible order of requests.

C programs cannot compact the heap. Compaction moves blocks in use together so that the gaps merge. It needs every pointer to a moved block to be updated, and C cannot find them all, because any variable, or any copy of the bytes of one, might hold an address. Systems that compact give the program handles, references that go through a table the allocator controls, instead of raw addresses. A buffer whose address has been given to hardware, for example to a DMA §4.36 (direct memory access) controller that copies data without the processor, must not move at all.

Remedies trade one cost for another. A pool of fixed-size blocks removes external fragmentation but wastes space inside blocks and reserves memory for one size. Allocating every long-lived object once at start-up and never freeing it keeps that memory unfragmented, but fixes the amount at start-up. Separate heaps for short-lived and long-lived data stop long-lived blocks from splitting the space of short-lived ones, but each heap can run out while another still has room.

Virtual memory changes the picture but does not remove the problem. On a computer with a memory management unit §6.9, the hardware that maps the addresses a program uses onto physical memory, a block that is contiguous in addresses can be scattered over physical memory, so physical memory is not what runs out in pieces. The heap’s range of addresses still fragments. A microcontroller §6.1 without such hardware has only physical addresses, so the layout of the heap is the layout of the memory.

Questions answered

What is the largest allocatable block versus total free memory?

The total free memory is the sum of all free bytes in the heap, while the largest allocatable block is the biggest single request the allocator can grant right now, and it is limited by the largest free piece, not by the total. The heap is the memory from which a program obtains blocks while it runs. A block must be one unbroken range of addresses, so a request succeeds only if one free piece can hold it, together with the allocator’s header (the bytes the allocator keeps to record the block’s size) and the rounding of the size up to the required alignment.

The two numbers differ when free memory is fragmented, meaning split into pieces between blocks still in use. In a 1024-byte heap whose free memory is two pieces of 200 bytes separated by a block in use, the total free memory is 400 bytes, but with an 8-byte header the largest allocatable block is 192 bytes, and a request for 300 bytes fails. A system that must keep serving requests should monitor both numbers: a steady total with a shrinking largest block means growing fragmentation, while a falling total means a leak or growing use.

Related entries: Memory leak (§4.8), Alignment (§4.22), Direct memory access (DMA) (§4.36), Static, stack, and heap storage (§4.11).