Building malloc from Scratch (Part 1): Architecture & Core Concepts
I wanted to understand how malloc actually works under the hood. Most explanations I found online described what an allocator does, but completely skipped over the "why" behind its design decisions. Rather than stopping at theory, I decided to build a cross-platform allocator in C that implements malloc , calloc , realloc , and free from scratch. This article documents the design of that allocator, the architectural tradeoffs I faced, and the core concepts I had to learn along the way. Table Of Contents Design Decisions Architecture Modern Allocator Strategies Core Concepts What's Next Project Overview A custom memory allocator does not create physical memory. Instead, it requests pages of raw virtual memory from the operating system and manages how that memory is partitioned, reused, resized, and released by the application. The goal of this educational project is to implement C's core memory management API using a modular, cross-platform architecture inspired by design principles found in modern allocators, rather than relying on legacy, single-platform tricks. Design Decisions #1: Why I am Skipping sbrk While many classic tutorials use sbrk for educational implementations, I deliberately chose a 100% mmap -based approach for two major reasons: sbrk is a fragile global bottleneck. It works by moving a single pointer (the program break) up and down. This means the allocator assumes it owns a contiguous line of memory. If a third-party library or another thread in the program secretly calls sbrk behind the scenes, the allocator's memory layout can break instantly. mmap , by contrast, provides isolated, independent chunks of memory. Cross-Platform Symmetry. Windows has absolutely no equivalent to sbrk , but it has a direct equivalent to mmap : VirtualAlloc . If we used sbrk , our architectural abstraction ( os_alloc ) would become awkward because Linux would deal with a moving pointer while Windows dealt with independent pages. Using mmap keeps the abstraction perfec