Skip to content

Implement a Memory Allocator

Over the past several months, I’ve spent a decent amount of time trying to understand how memory allocators work and implementing one myself. In this post, I’m documenting the allocator’s current design, its shortcomings, and plans for future extensions. While the allocator is neither as sophisticated nor as optimized as a production-grade allocator, it is also much more than a simple single-heap bump allocator, and I’ve tried to incorporate ideas used in production allocators (glibc in particular).


Starting out, I knew very little about memory allocators and had almost no experience with low-level memory management. Looking back, I wish I had developed the right intuition early on, so let’s first try to summarize what a memory allocator does in a few sentences.

In an operating systems course, we learn that malloc allows programmers to dynamically allocate heap memory. When a process requests heap memory from the OS, it typically does so in page-sized units (e.g., 4KB). The allocator then carves these large regions into smaller chunks as the program calls malloc. At a high level, a memory allocator is just a system that holds on to large regions of memory, handing out smaller chunks as they are requested and reclaiming them once they are freed.

When implementing a memory allocator, we often need to write data directly in memory. For example, right before the chunk payload, we might store an 8-byte header that contains chunk metadata. At first, I felt a bit lost — why not just use a dictionary that maps chunk_id to chunk_size? The point I’m trying to make is that memory allocators operate at a much lower level than one might initially expect. Data structure libraries often use malloc, so the allocator cannot depend on them without creating a circular dependency. Realizing this made me appreciate how fundamental memory allocators are and gave me a better sense of how to write code that operates close to the OS.


design

We typically imagine the heap as being a contiguous region of memory that grows toward the stack. In practice, allocators can use mmap to obtain regions elsewhere in the process’s virtual address space, so dynamically allocated memory does not have to be strictly contiguous. Memory-mapped regions, called ā€œheapsā€ in memory allocators, can be linked and form a linked list. An arena holds the allocator state, including the head of this list.

(In glibc, single-threaded programs use only the main arena, which typically grows or shrinks the contiguous heap using sbrk. Multi-threaded programs can use additional arenas backed by memory-mapped regions to reduce lock contention.)

In my current design, the tail of the linked list is treated as the active heap. When there is no suitable chunk in the free list, a new chunk is carved from the active heap (more on this later).

typedef struct arena {
int id;
heap_t *heaps;
heap_t *active_heap;
free_chunk_prefix_t* free_list[DEFAULT_FREE_LIST_MAX_BINS];
pthread_mutex_t lock;
} arena_t;

The default mapping size can be tuned (e.g., 16 MiB), but it is rounded up to the nearest page size. A special case is when the requested size is larger than the default mapping size. In this case, the allocator follows a separate path to mmap a region large enough to hold just that chunk.

A heap is unmapped and removed from the linked list only when it becomes entirely free. If even a single chunk is still in use, the entire heap remains mapped. This can lead to inefficient memory usage, so a future extension could explore ways to reclaim partially used heaps more effectively.

Each arena is protected by a lock, so only one thread can allocate from it or return freed chunks to it at a time. Using multiple arenas reduces lock contention, at the cost of potentially worse memory utilization. In my current design, a new arena is initialized whenever a new thread first uses the allocator, up to a limit of 64 arenas. Once we reach the limit, new threads are assigned to existing arenas in a round-robin fashion. Each thread continues to use its assigned arena.

For programs with many threads, having more arenas than CPU cores can help reduce contention. Although the number of threads executing simultaneously is limited by the available cores, the goal is to make those executing at the same time less likely to compete for the same lock.

Arena assignment does not control how the OS schedules threads. Two threads running on the same logical core still take turns, even if they use different arenas. Also, a thread that is preempted while holding an arena lock keeps the lock, so other threads that need that arena must wait until it runs again and releases the lock.


Now, let’s zoom in on one of the heaps and take a look at its layout. A heap is defined by its base, end, and the bump pointer, which marks the start of the unexplored region. If no suitable chunk in the free list can satisfy the current request, the allocator carves out a new chunk from the unexplored region of the active heap and advances the bump pointer. If the chunk immediately before the bump pointer is freed, the bump pointer is moved backward to reclaim the space for the unexplored region.

typedef struct heap {
arena_t *arena;
struct heap *next;
uint8_t *base;
uint8_t *bump;
uint8_t *end;
} heap_t;

Currently, heap_t is 40 bytes, which is stored at the base of the memory-mapped region. This seems to be a good place to pause and discuss how memory mapped regions are aligned.


We have two constraints:

  1. Chunk payloads must be 16-byte aligned to satisfy the ABI requirements.
  2. Memory mappings (mmap) use page-sized units.

Let’s first discuss normal heaps, then look at standalone mappings for large chunks.

In my current design, normal heaps are aligned to the default mapping size. For example, if the default mapping size is 16 MiB, each heap starts at a 16 MiB-aligned address.

Why is this necessary? When we free a chunk, we have to identify the heap and arena it belongs to. There can be remote-free scenarios where Thread A allocates a chunk and Thread B frees it, in which case we need to correctly identify and return the chunk to Thread A’s arena. With 16 MiB alignment, we can efficiently recover the heap’s base address where heap_t is stored by clearing the lowest 24 bits of the chunk’s address.

Although mmap returns a page-aligned address, it does not guarantee the specific alignment we need. To enforce this, I first map twice the default mapping size. This guarantees enough room for a full heap starting at a 16 MiB-aligned address. I then unmap any unused space before and after the heap.

While we can store heap_t at the start of the 16 MiB region, we also have to make sure that the first chunk’s payload is 16-byte aligned. This may require additional padding. In my current design, heap_t is 40 bytes and the chunk header is 8 bytes, so the payload is aligned without padding. The takeaway is that not all of the mapped region is available for chunks: some space is needed for bookkeeping and any initial padding.

[ heap_t + padding ]
[ header (size | flags) ] First chunk header
[ payload ... ] First chunk payload <- 16B aligned

For memory regions reserved for large chunks, we only need the chunk header without any heap metadata. After mmap, we place the header at the first offset that makes the payload 16-byte aligned. When we free the chunk, we need the mapping’s base address and size, rather than just the chunk size. Given this fixed layout, we can always recover the base address by rounding the header address down to a page boundary, then compute the mapping size by rounding the header’s offset plus the chunk size up to a page-size multiple. Neither value needs to be stored separately.


When a chunk is freed, it is pushed to the front of the linked list of free chunks. Note that the head of the free list is part of the arena state, so free chunks from all heaps from the same arena are linked together.

For faster lookup, the free list is divided into size classes, with a separate linked list for each class. Both in-use and free chunks need enough space to store their metadata, so a chunk cannot be smaller than a certain minimum size. In my current design, the minimum chunk size is 32 bytes, and all chunk sizes are multiples of 16 bytes. So freelist[0] holds 32-byte chunks, freelist[1] holds 48-byte chunks, and so on. The last list is an oversized bin that holds all chunks too large for the other size classes.

free_chunk_prefix_t* free_list[DEFAULT_FREE_LIST_MAX_BINS];

Before a chunk is pushed to the free list, we check its neighboring chunks to see if either of them is free. If so, we merge the adjacent free chunks into a larger one, increasing the likelihood that the chunk can be reused for future allocations.

When a user calls malloc, the allocator first computes the actual chunk size from the request size, accounting for the header and alignment. It then checks the free list bin for that exact size. If the bin is empty, it searches progressively larger bins for a chunk that can satisfy the request. For exact-size bins, checking the head of the linked list is enough. For the oversized bin, we may need to traverse the list to find a suitable chunk.

If no suitable chunk is found in the free list, the allocator tries to carve a new chunk from the unexplored region of the active heap. If the unexplored region cannot satisfy the request, the allocator maps a new heap, adds it to the arena’s heap list, update the active heap, and carves the chunk from the new heap.

Note that the free list does not maintain chunks in memory-address order. Freed chunks are pushed to the front of the list, so the actual links may be more tangled than what the simplified diagram suggests.

Also note that we do not maintain a linked list of in-use chunks. When the programmer calls free, they pass the payload pointer returned by malloc as a parameter, and the allocator can use pointer arithmetic to locate the chunk header and free the chunk.


As mentioned several times, a chunk header is stored immediately before the payload.

The size of the chunk includes the header, any alignment padding, and space for a footer when the chunk is free, so it is larger than the size requested by the user. The minimum chunk size is 32 bytes, and all chunk sizes are multiples of 16 bytes. With the first chunk’s payload aligned to 16 bytes, this ensures that every subsequent chunk’s payload is also 16-byte aligned.

In-use and free chunks have different headers because they store different information. Let’s first look at an in-use chunk.

In-use chunk header
[ header (size | flags) ] 8 bytes
[ payload ... ]

An in-use chunk has an 8-byte header followed by the payload. This word stores the chunk size and the state flags. In my current design, chunk sizes are multiples of 16 bytes, so the lowest four bits are always zero and can be reused as flags. Bit 0 (the P-bit) indicates whether the previous chunk is free, and bit 1 (the M-bit) indicates whether the chunk belongs to a separate mapping rather than an arena.

As discussed earlier, if the M-bit is set, we can unmap the region directly when the chunk is freed.

The P-bit is useful when a chunk is freed because it tells the allocator whether the chunk can be merged with its predecessor. The allocator can locate the next chunk using the current chunk’s size and inspect its header to determine whether it is free. Locating the previous chunk is more tricky because its size is not stored in the current header. Free chunks therefore store a footer containing their size. If the P-bit is set, the allocator can read the footer immediately before the current header and use it to locate the previous chunk’s header.


Next, let’s look at a free chunk. A free chunk stores additional pointers that serve as links in the doubly linked free list. As discussed earlier, it also has a footer that mirrors the chunk size stored in the header.

Free chunk header
[ header (size | flags) ] 8 bytes
[ fd ] 8 bytes, forward pointer to the next free chunk
[ bk ] 8 bytes, backward pointer to the prev free chunk
...
[ footer (size ) ] 8 bytes, mirrors the header, but flag bits are cleared

Lock contention cannot be entirely avoided as long as multiple threads share the same arena. One way to minimize this overhead is to use thread caches.

The idea behind thread caches is that when a thread frees a chunk, the thread holds onto it instead of immediately returning it to the arena. From the arena’s perspective, the chunk is still marked as in use, and only the thread that owns the cache can reuse it. This can also improve locality by encouraging threads to reuse chunks that were freed recently.

In C, thread caches are implemented using thread-local storage. If a variable is declared with the _Thread_local keyword, each thread gets its own separate instance.

static _Thread_local tcache_bin_t g_tcache[TCACHE_MAX_BINS];

Like free lists, thread caches are divided into size classes. But unlike free lists, they have no oversized bin, so chunks too large for the cache are returned to the arena. The thread cache also has limited capacity, and chunks can be added only when there is space.

In my current design, I don’t explicitly flush or evict chunks from the thread cache. This means a chunk can remain cached for a long time without being reclaimed by its owning arena. A possible extension would be to explore ways to manage thread caches more effectively.

Note that in a remote-free scenario, a chunk belonging to Thread A’s arena may be placed in Thread B’s thread cache and reused by Thread B. This does not violate correctness as long as the chunk is returned to its owning arena when it leaves the cache.


Now that we are familiar with the overall design, let’s look at the pseudocode for malloc, free, calloc, and realloc to see how everything fits together.

void *malloc(size_t requested_size) {
1. Compute the chunk size, including
the header and alignment.
2. If the total size exceeds the default heap size,
use the large-allocation path.
3. Check the thread cache for a suitable chunk.
4. If a chunk is found, return a pointer to its payload.
5. Otherwise, acquire the arena lock and search the free list.
6. If a suitable chunk is found, split it if the remainder would be
at least the minimum chunk size. Release the arena lock and
return a pointer to the payload.
7. If no suitable free chunk is found,
carve a new chunk from the bump region.
8. Release the arena lock and return a pointer to the payload.
}
void free(void *ptr) {
1. If the chunk is small enough for the thread cache, try to add it.
If the cache has available capacity, add the chunk and return.
2. Otherwise, acquire the arena lock.
3. Mark the chunk as free and coalesce it with neighboring free chunks.
4. If the resulting free chunk is adjacent to the bump pointer,
move the bump pointer backward.
5. Otherwise, add the chunk to the arena’s free list.
6. Release the arena lock.
}
// calloc allocates (count * size) bytes, initialized to zero.
void *calloc(size_t count, size_t size) {
1. Check whether (count * size) would overflow.
If so, return NULL.
2. malloc count * size bytes.
If allocation fails, return NULL.
3. Set the allocated bytes to zero via memset.
4. Return a pointer to the payload.
}
// realloc resizes the payload and returns a pointer to the new payload.
// Existing contents are preserved up to the smaller of the old and new sizes.
void *realloc(void *ptr, size_t requested_size) {
If the chunk was directly mmaped:
If the requested size is smaller than the current size:
Unmap unused trailing pages if possible.
Update size in the chunk header.
If the requested size is larger than the current size:
If the current mapping can satisfy the request:
Update size in the chunk header.
Otherwise:
Map a new region.
Copy the existing contents and unmap the original region.
Update ptr to point to the new payload.
Otherwise, if the chunk is part of an arena:
If the requested size is smaller than the current size:
Split the chunk if the remainder would be at least
the minimum chunk size.
If the requested size is larger than the current size:
If the next chunk is free and merging provides enough space:
Merge the chunks and split off any usable remainder.
Otherwise:
Allocate a new chunk.
Copy the existing contents and free the original chunk.
Update ptr to point to the new payload.
Return ptr.
}

The allocator’s design focuses heavily on improving multithreaded throughput, so I wanted to measure that improvement in a meaningful way.

Initially, I wrote a simple program that creates N threads, each of which repeatedly allocates and immediately frees objects. While this program showed a drastic performance improvement, it felt a bit contrived. I wanted a more realistic workload so that when I say ā€œI tested my allocator on X,ā€ people have a fairly good idea of what the allocation patterns looked like.

Coming up with a suitable workload was not easy. I wanted it to be recognizable and intuitive. If I said I tested my allocator on a custom game, I would also have to explain how the game works or how it is implemented to discuss its memory usage. So I tried to think of simpler workloads, but those tend to have less interesting allocation patterns. For example, I initially considered building a trie, but with fixed-size nodes, every node allocation would request the same size. This could heavily favor size-segregated free lists and thread caches, and it felt like choosing a workload that played to my allocator’s strengths.

I eventually designed a JSON parsing workload. JSON parsing seemed like a good candidate, as JSON can be nested and contain different types, leading to varied allocation sizes and patterns. I used an open-source JSON parser called cJSON. cJSON represents JSON as a tree of fixed-size nodes, but it also allocates buffers of varying sizes for string values and object keys.

The program I wrote is straightforward. It creates N threads, and each thread processes the same input JSON file. A more realistic workload could use a shared work queue to distribute records from the same file among threads. But since the JSON files I have aren’t that big, I have each thread parse the entire file. To increase the workload, I made it possible for each thread to make multiple passes over the file. The allocation pattern is simple: each thread parses a JSON record and immediately frees the resulting tree.

The program reports elapsed wall-clock time at the end. The timer starts when all threads have been created and are ready to run. There is no synchronization between threads during the parsing phase, though the allocator uses locks internally.

I tested my allocator under two configurations. The baseline uses a single arena with thread caches disabled, while the other uses multiple arenas and thread caches. I used the twitter.json dataset found here. I used 8 threads, each parsing and freeing 100 tweets in the dataset 100 times, for a total of 10,000 tweets processed per thread. The machine I used has 8 cores and 16 logical CPUs.

Across ten runs, the baseline’s average elapsed time was 10.765901 s. Multiple arenas and thread caches reduced that to 0.596619 s. This isn’t really surprising, and again, the setup does feel a bit rigged to prove a point. Still, I didn’t expect the improvement to be this large on an 8-thread workload, and I think it’s a good exercise to work with concrete measurements.


I think it’s good practice to be able to explain and discuss my projects, especially the challenges I faced. So here is a brief reflection on the project so far.

First, my C was rusty, so I struggled to get used to pointer arithmetic and working with raw bytes. Now, I feel much more comfortable navigating C.

This was also really my first project where it felt like careful testing mattered; there were just too many edge cases and memory errors, and it took some time before I became confident in my allocator’s correctness. Some of the bugs I had especially hard times with:

  • Last chunk before the heap bump: The chunk immediately before the heap bump needs special treatment. For example, it shouldn’t try to merge with its right neighbor during free. This is trickier than it sounds because the chunk layout stores minimal metadata, so we often rely on neighboring chunks for information. For example, the chunk header only indicates whether the previous chunk is free; determining whether the next chunk is free is less straightforward.
  • Remote frees: Remote frees were something I hadn’t really thought through at the start of the project. It took some time before I realized what could go wrong, and a major refactoring was needed to identify a chunk’s owning heap without explicitly storing a heap pointer in the chunk header. I wish I had spent more time clarifying the design requirements at the beginning, which could have saved a lot of time later.

Lastly, working on a memory allocator really forced me to understand how compilers and low-level libraries work. For example, there were times when the compiler optimized away malloc and free in my test programs. I also had a lot of trouble with printf; I didn’t know it could call malloc internally, so using it for error logging created a circular dependency. I became much more comfortable digging beneath the surface to identify the root causes of problems.


Hopefully, this is a complete and easy-to-follow summary of the allocator I’ve implemented so far. As I continue tinkering with it, I’ll revisit this post to reflect any design changes.