Projects / Memory allocator
C++ · about 10 hours · 4 phases
Build a memory allocator in C++
Every new and malloc in your programs asks someone else's code for memory, and that code makes choices that cost you time and sometimes correctness. How does it find a free spot? What happens when you free in a strange order? Why is it sometimes slow? The best way to answer is to write one. In about 10 hours you will build three small allocators in C++, measure them, and then add the debugging features that catch the classic bugs: overflows, double frees and leaks.
You work in four phases of about 2.5 hours each, and every phase ends with something you can run. By the end you will have:
- an arena that is several times faster than
newfor one job, and a clear idea of when it is the wrong tool, - a heap with
allocateanddeallocatethat splits and merges blocks, plus a checker that proves its layout is sound, - a pool for same-sized objects that plugs into
std::list, - a debug mode that reports overflows, double frees, bad pointers and leaks.
You need basic C++ (pointers, classes, templates at the level of std::vector<int>). Anything more is explained when it first shows up.
If pointers still feel shaky, spend an evening on them first and then come back. Every phase uses them.
The four phases
The arena
You end with an allocator you can explain in one sentence, measured against new.
- 1.1 Hand out the next bytes30 min
- 1.2 Alignment, the part that bites40 min
- 1.3 How fast is "one assignment"?40 min
- 1.4 When an arena is the right tool40 min
A heap that frees
You end with allocate and deallocate for any size, with a checker that proves the layout is valid, and a measured fragmentation problem.
- 2.1 Blocks with headers50 min
- 2.2 Free, and merge the neighbours40 min
- 2.3 Fragmentation30 min
- 2.4 Prove it with a stress test30 min
Fast for one job
You end with a pool allocator for same-sized objects that works with standard containers, and a benchmark that shows where each allocator wins.
- 3.1 Why our heap is slow35 min
- 3.2 A pool for one size55 min
- 3.3 Plug it into std::list30 min
- 3.4 Measure everything30 min
Catch the bugs
You end with a heap that reports overflows, double frees, bad pointers, use after free and leaks.
- 4.1 Guard bytes30 min
- 4.2 Report, don't crash40 min
- 4.3 Break it on purpose40 min
- 4.4 Does the good path still work?40 min