THINK FIRST·CODE LATER

← All labs

The Linux buddy allocator

Problem

Simulate a buddy allocator.

Input: total memory (a power of two) and the minimum block size (a power of two), then alloc NAME size / free NAME operations.

  • alloc: round the size up to a power of two (at least the minimum). Take the smallest free block that is large enough (lowest address among equal sizes); split it in halves repeatedly, keeping the lower half and putting the upper half on the free list, until it has the right size. Print alloc A 70 -> block 128 at 0 (splits 3, internal waste 58) or alloc X 900: FAILED (needs a 1024 block).
  • free: repeatedly merge the block with its buddy (address XOR size) if the buddy is free with the same size. Print free D -> free block 256 at 0 (merges 2).

At the end print Free blocks: 64@192 … sorted by size then address (or none) and Allocated: B in blocks for R requested, internal fragmentation F (P%) — omit the percentage when nothing is allocated.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.