Growing an arena with virtual memory
What you'll learn: How to use operating system tricks to create a memory arena that starts small but can grow to a massive size without moving in memory.
The problem with fixed buffers
In previous lessons, we built arenas using a fixed-size array (like char buffer[1024]). The problem is obvious: if you run out of space, you’re stuck. If you try to realloc that buffer, the entire arena might move to a new address, which breaks every pointer you’ve already saved. We need a way to expand the arena's capacity while keeping its starting address exactly where it is.
The "Library Table" analogy
Imagine you are studying in a massive library. You go to the librarian and say, "I might need 100 tables today, but for now, I only want to actually sit at one."
The librarian reserves a long row of 100 tables just for you. No one else can sit there. However, the lights are turned off at tables 2 through 100. If you try to sit there, you’ll trip in the dark. When you finish with your first table and need more space, you ask the librarian to commit the next table by turning on the lights. You haven't moved; you just gained access to the space you already claimed.
Reserving vs. Committing
On modern systems, we can do this using mmap (Unix) or VirtualAlloc (Windows). We ask the OS for a huge range of virtual address space (Reserving). This doesn't actually use your physical RAM yet. As your arena fills up, you tell the OS to back that specific address range with actual physical memory (Committing).
// Concept: Growing an arena using virtual memory (POSIX style)
#include <sys/mman.h>
#include <stddef.h>
typedef struct {
unsigned char *base;
size_t committed;
size_t reserved;
size_t used;
} Arena;
// Reserve a giant block of addresses, but use 0 physical RAM
Arena create_arena(size_t max_size) {
Arena a = {0};
a.reserved = max_size;
a.base = mmap(NULL, max_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
return a;
}
// When you need space, "turn on the lights" for a new chunk
void arena_grow(Arena *a, size_t size) {
size_t new_commit = a->used + size;
if (new_commit > a->committed) {
// Tell the OS to actually provide physical RAM for this range
mprotect(a->base + a->committed, 4096, PROT_READ | PROT_WRITE);
a->committed += 4096; // Usually done in "pages" of 4KB
}
}
Why this rules
By reserving a large chunk of virtual address space (e.g., 1GB) upfront, the base pointer never changes. You can keep handing out pointers to your program, and they will remain valid forever. You only "pay" for the memory in actual RAM usage when your arena pointer actually reaches that part of the reservation.
Key takeaway
Virtual memory allows you to reserve a huge continuous address range for your arena without consuming physical RAM until you actually need it.