What is a Memory Arena
What you'll learn: You will understand how to manage memory as a single, large block rather than many tiny, scattered allocations.
The Buffet Tray Analogy
In standard C programming, we often use malloc() to request small, specific amounts of memory. Imagine you are at a party, and every time you want a single cracker, you have to find the host, ask for a tiny plate, and wait for them to hand it to you. If you want ten crackers, that’s ten separate trips and ten tiny plates to wash later. This is slow and leads to "fragmentation"—a table cluttered with empty plates.
A Memory Arena (also called a region or zone) is like taking a large cafeteria tray to the buffet. You ask the host for one giant tray at the start of the night. Whenever you need a cracker, a piece of cheese, or a napkin, you simply place it on your tray. You don't ask the host for anything new; you just use the space you already have. When you are done with the party, you hand back the entire tray at once.
How it Works in Code
Instead of calling free() a hundred times for a hundred different pointers, an arena allows you to allocate one large buffer of bytes and "carve" pieces out of it by moving a marker forward.
#include <stddef.h>
#include <stdint.h>
typedef struct {
size_t size;
size_t offset;
uint8_t *buffer;
} Arena;
// To "allocate" from the arena, we just move a pointer forward
void* arena_alloc(Arena *a, size_t size) {
if (a->offset + size <= a->size) {
void *ptr = &a->buffer[a->offset];
a->offset += size; // Move the "marker" forward
return ptr;
}
return NULL; // Out of space!
}
// To "free" everything, we just reset the marker to zero
void arena_reset(Arena *a) {
a->offset = 0;
}
Why Use an Arena?
- Speed: Moving a marker (an integer addition) is much faster than the complex logic
malloc()uses to find a free hole in memory. - No Leaks: You don't have to track every individual pointer. As long as you free the one big "tray" at the end, everything is cleaned up perfectly.
- Locality: Because all your data is sitting right next to each other on the same tray, your CPU can access it more efficiently.
Key takeaway
A memory arena improves performance and simplifies cleanup by treating a large pre-allocated block as a private pool for smaller objects.