What is malloc doing, anyway?
An article walks through building a toy memory allocator in C from scratch, explaining sbrk, chunk headers, free lists, demand paging, and mmap before comparing performance against glibc.
read it It offers a clear, hands-on code walkthrough of how memory allocators manage heaps, system calls, and fragmentation under the hood.
summary
The post demonstrates how C's malloc avoids expensive system calls by maintaining a userspace memory pool via sbrk and mmap. It builds a toy allocator step-by-step, implementing free lists, chunk splitting, coalescing, and trimming to reclaim memory. Benchmarks show how these mechanisms trade off execution speed and memory overhead compared to glibc's sophisticated binning and tcache strategies.
key points
- Small allocations use sbrk to grow a single contiguous heap, whereas requests over 128 KiB use anonymous mmap for direct page-level allocation and freeing.
- A basic bump allocator runs 22.7 times faster than raw sbrk calls, but a functional free list allocator runs significantly slower than glibc due to linear list traversal.
- Glibc achieves high performance through size-specific bins and thread-local caches (tcache), though caching can prevent memory from being immediately returned to the kernel.
who should read it
Systems programmers and C developers wanting to understand the low-level mechanics of memory allocation and heap management.
discussion positive
consensus
Commenters note that while the post provides a great educational foundation, real-world high-concurrency systems rely on modern allocators like jemalloc or mimalloc that eschew sbrk.
pushback
Some argue that dynamic memory can often be avoided entirely in C through static allocations or stack-only patterns, eliminating heap overhead completely.
This is mostly describing a kind of obsolete allocator that uses the brk to adjust a single contiguous heap range. This is basically irrelevant with virtual memory and mmap. The good malloc impls (jemalloc, mimalloc) don't do this.
It contextualizes the article's approach by pointing out that modern production allocators avoid brk entirely in favor of scalable alternatives.
Generated by an LLM from the article and thread. Check the sources before relying on it.