Introduction
Every call to malloc asks an allocator to find space in the heap. This simulator makes that process visible: you allocate and free blocks and watch the heap map change, then compare placement strategies on the same workload.
Problem statement
Objectives
- Implement the data structures behind a real allocator
- Split and coalesce blocks correctly
- Measure external fragmentation
- Compare placement policies experimentally
Features
- first / best / worst-fit strategies
- Alignment to 8 bytes
- Coalescing with both neighbours
- ASCII heap map and block list
- Fragmentation statistics and a strategy comparison
Concepts demonstrated
- Heap management
- Fragmentation
- Placement algorithms
- Doubly linked lists
System architecture
Each Block records its offset, size, used flag and allocation ID, linked in address order. heap_alloc chooses a block by strategy, splits off the remainder as a new free block, and marks it used. heap_free marks a block free and merges it with a free successor and predecessor. Fragmentation = 1 − largest free block / total free.
Folder structure
Complete source code
Makefile
What each file does
- src/allocator.h
Block,Heap, strategies and the API.- src/allocator.c
- Choosing, splitting, coalescing, the heap map and statistics.
- src/main.c
- Command interpreter and the strategy comparison workload.
- Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
alloc 100 alloc 200 alloc 50 alloc 300 map free 2 free 3 map alloc 120 alloc 500 stats free 1 free 4 map init 512 best alloc 64 alloc 128 alloc 64 free 2 alloc 40 map compare quit
Testing
- Diff with
tests/expected-output.txt. - Free every block and confirm the heap returns to one free block of the full size.
- Run
compareand explain why best-fit leaves the least fragmentation for this workload.
Common errors
Heap shows two adjacent free blocks
Coalescing must check both next and prev after freeing.
Allocated sizes are not multiples of 8
Round requests up with align_up before searching.
Possible improvements
- Next-fit and buddy-system strategies
- Segregated free lists for common sizes
- A trace file of alloc/free commands for repeatable experiments
Additional challenges
- 1Implement the buddy allocator and compare its internal fragmentation.
- 2Add
reallocthat grows in place when the next block is free. - 3Plot fragmentation over a long random workload.
Built and tested it yourself? Mark it to update your dashboard.