Buddy System Example
This page gives some examples showing how the buddy system works.
This page may not display
well with a narrow browser window; widen it if you need.
The block's sizes should be proportional, but won't be
exact, due to rounding in the sizes, and having to fit the text in the box.
When allocating, and choosing among nodes of the same size, I always
choose the left-most. Of course, this is not an essential of the algorithm.
It's all HTML with heavy uses of style sheets; It looks good in
Firefox, but I don't have time to try IE just now.
Suppose we have 16K to manage. It starts as one large block:
Now, we have a request A for a block of 3.6k. We round up to 4K and
perform two splits to create such a block.
Next, handle request B for 1.5K. This rounds up to 2, requiring another split:
4K
(A)
2K
(B)
2K
(free)
8K
(free)
Now service allocations of 1.2K (C), 1.9K (D) and 2.7K (E):
4K
(A)
2K
(B)
2K
(C)
2K
(D)
2K
(free)
4K
(E)
Of course, nodes are merged when possible. Suppose the C allocation is
freed:
4K
(A)
2K
(B)
2K
(free)
2K
(D)
2K
(free)
4K
(E)
Then, if B is also freed, the buddies are merged back into a larger
node.
4K
(A)
4K
(free)
2K
(D)
2K
(free)
4K
(E)
However, it is only possible to join nodes which were previously split.
For instance, suppose we process two more allocations, for 1.5K (F)
and 1.6K (G), which will
cause another split:
4K
(A)
2K
(G)
2K
(free)
2K
(D)
2K
(F)
4K
(E)
Then perhaps that D is freed:
4K
(A)
2K
(G)
2K
(free)
2K
(free)
2K
(F)
4K
(E)
Now, even though there are two adjacent free blocks
of the same size, they cannot be
merged because they were not the result of splitting a larger block.
Now suppose A is released:
4K
(free)
2K
(G)
2K
(free)
2K
(free)
2K
(F)
4K
(E)
If G is then freed, it results in two merges.
8K
(free)
2K
(free)
2K
(F)
4K
(E)
And some more operations: allocate 6.8K (H), release E, allocate 850 bytes (I):
8K
(H)
1K
(I)
1K
(free)
2K
(F)
4K
(free)
Allocate 610 bytes (J); allocate 1.6K (K); allocate 750 bytes (L); release H.
8K
(free)
1K
(I)
1K
(J)
2K
(F)
2K
(K)
1K
(L)
1K
(free)
Allocate 3.9K (M); allocate (N) 1.7K; release L; release F;
4K
(M)
2K
(N)
2K
(free)
1K
(I)
1K
(J)
2K
(free)
2K
(K)
2K
(free)
Release K; allocate 670 bytes (P); release I.
4K
(M)
2K
(N)
1K
(P)
1K
(free)
1K
(free)
1K
(J)
2K
(free)
4K
(free)
Release N; release J.
4K
(M)
2K
(free)
1K
(P)
1K
(free)
8K
(free)