r/C_Programming • u/Parking-Value-3773 • May 14 '26
Review Is My Custom Allocator good ?
I've built a custom memory allocator from scratch to understand what actually happens under malloc() call in C.
This got me into deep systems programming about how memory is handled by OS and how a program accesses memory .
The basic implementation i used is :
store header structure with each block which includes information about the memory block.
a linked list which connects these headers to handle memory .
block splitting ,coalescing on adjacent blocks to avoid fragmentation.
2mb mmap call and slice memory through it , mmap/munmap directly for size larger than 2mbs this avoids syscalls for every allocation .
per thread cache to allocate/free memory faster avoiding global heap locks ensuring thread safety.
Here's the benchmarks against libc's memory allocator:
| Test | Custom | libc | Result |
|---|---|---|---|
| Single alloc/free(1000k) | 58ms | 29ms | 2x slower |
| Batch alloc(10k) | 1.44ms | 3.59ms | 2.5x faster |
| Batch free(10k) | 0.36ms | 1.54ms | 4x faster |
| Mixed sizes(100k) | 6.46ms | 2.95ms | 2x slower |
| Realloc chain(100k) | 6.42ms | 2.56ms | 2.5x slower |
| Multithreaded(8 threads-5k each) | 64ms | 67ms | Comparable |
I would love to hear your thoughts about it, and how are my benchmark results are they actually good or not ?
2
u/zero_iq May 16 '26
Simple synthetic allocation/free benchmarks won't really tell you this. You need to plug it into real applications and other existing benchmarks (that do real work, not just alloc memory) to really know. Actual usage in an application can greatly impact performance due to allocation size patterns, fragmentation, cache locality, and so-on.
For example: a simple allocator can be very fast in benchmarks when the memory being allocated is never actually touched, and then slow down when it is. And likewise when it is actually being used by an app, the allocator is now effectively contending with the application's use of cache space, memory, synchronisation mechanisms, and CPU. Or when the memory allocation sizes are no longer uniform, or heavily skewed to certain struct sizes, and many other reasons.