Binary Buddies
Introduction
This document explains the binary buddy system.
info
This implementation is more complex than buckets or linked-lists, but provides low fragmentation and systematic block merging.
Main characteristics:
- Low fragmentation.
 - Allocation may be slow.
 - Complexity and performance highly depend on additional data structures used to track free blocks.
 
Principle
- Manage a contiguous memory region of size 
n(withna power of two). - This region can be:
- Given to the user as a whole
 - Split recursively into two equal halves.
 
 - The two halves are called buddies.
 - Each block’s (divided or not) size is always a power of two, with a predefined minimum block size.
 
Binary Buddies Structure
Memory Management
Allocation
- User calls 
malloc(s). - Compute 
s2p = smallest power of two ≥ s + metadata_size. - Find the smallest available block of at least 
s2p. - If the block is more than twice the requested size, split recursively into buddies until the block matches 
s2p. - Return the address of the buddy and mark it as used.
 
Free
- Mark the block as free.
 - If its buddy is also free, merge them into a larger free block.
 - Repeat recursively until no further merge is possible.
 - If the whole page is free, it can be unmapped.
 
Metadata
Each block stores metadata:
- Block status (allocated/free).
 - Block size (power of two).