← All projects

03 / Memory management

Buddy allocator

This is my C experiment with buddy allocation: keeping free lists, splitting blocks for allocations, and merging them on release.

CLearning experiment
View repository

The problem

A memory allocator must find space for a request while keeping track of what remains available. Repeated allocations and releases make that bookkeeping more interesting than moving a single pointer.

How it is structured

The implementation organizes free blocks by size level. Allocation searches for an available level and splits larger blocks; release checks for a free buddy and combines blocks as it moves back through the levels.

Free lists

Free-list helpers insert, find, remove, and pop blocks. Keeping those operations separate exposes the data-structure work behind allocation and release.

Allocation and release

The allocation and release functions make splitting and recombination inspectable. Debug output and a small main routine provide a starting point for tracing the lists.

Current capabilities

  • Block metadata and size-indexed free lists.
  • Allocation by splitting a larger free block.
  • Release logic that searches for a buddy and attempts to coalesce space.

Scope & limitations

This isn’t a replacement for malloc. Behavior across arbitrary request sizes, fragmentation, invalid frees, and concurrent access still needs thorough testing. The walkthrough below explains the idea; it doesn’t run the C code.

Illustrative walkthrough / Buddy allocation

A single free block

Start with 64 illustrative units of memory. A request for 16 units needs a smaller block.

1 / 6
This is a simplified illustration, not the C allocator running in your browser. The units are arbitrary, and metadata overhead and edge cases are left out.

A detail worth looking at

One detail to watch is the free list after a release. A block can only merge with its buddy when that buddy is also free; the total amount of free memory doesn’t tell the whole story.

Explore the source