Projects / Memory allocator / Wrap up
Wrap up
Keep going
- Size classes. Keep one free list per size (16, 32, 48, ...) so
allocateis a lookup, not a scan. This is the single change that fixes the slow heap. - Next fit or best fit. Compare placement strategies for fragmentation on your own workload.
- Threads. Add a lock, measure it, then give each thread its own pool.
- A global
operator new. Replace it with your heap and run a real program. - Return memory to the OS. Our buffer is fixed; real allocators grow with
mmapandsbrk.
What this version leaves out, and what a real allocator does
- glibc
malloc, jemalloc and tcmalloc keep many size-segregated free lists, per-thread caches and separate paths for tiny, medium and huge requests. Huge ones go straight to the operating system. - They grow and shrink as the program needs, where ours has a fixed buffer.
- They take locks or use per-thread state, and ours is single-threaded.
- They aim for low fragmentation over long runs, which our tests do not exercise.
- Real debugging tools (AddressSanitizer, Valgrind) check every byte access, not only a guard at the end of a block.
Check yourself
Answer each question in your head first, then open it to check.
Why does
Arena::allocround the address up, and what goes wrong if it does not?Types need their address to be a multiple of their alignment. Misaligned access is slower or a crash on some CPUs, and it is undefined behaviour in C++ everywhere.In
deallocate, why must freeing merge with the previous block, and what field makes that possible?Without merging, freed neighbours stay as small separate holes and large requests fail even though enough contiguous space is free. Theprev_sizefield tells us where the previous block starts, because we cannot walk backwards otherwise.Why did our heap take seconds where
operator newtook milliseconds, and what is the standard fix?First fit scans from the start past every used block, so each allocation costs time proportional to the number of live blocks. The fix is to keep free lists, usually one per size class, so the allocator never looks at used blocks.How does a pool store its list of free slots without any extra memory?
A free slot is unused, so its first bytes hold the pointer to the next free slot. The slot must be at least the size of a pointer.Teach it back: a teammate says the canary check proves the program has no buffer overflows. What do you answer?
It only catches writes that reach the guard when a block is freed. Writes into padding, writes to other blocks, and overflows in blocks that are never freed all go unnoticed. It reduces risk, and tools that check every access are stronger.
Sources
- cppreference: Allocator requirements, the interface our
PoolAllocatorimplements. - cppreference: alignof, what alignment means in C++.
- Clang: AddressSanitizer, the tool mentioned in Step 4.4.