Linear or Bump allocators
What you'll learn: How to manage memory efficiently by treating a large block of bytes like a simple stack of trays.
The Problem with Standard Allocation
Normally, when you use malloc(), the computer has to search for a hole in memory that is just the right size. When you free() it, the computer has to bridge those holes back together. This is flexible, but it’s slow and leads to "fragmentation"—a mess of tiny gaps that are hard to reuse.
The "Stack of Trays" Concept
Imagine a cafeteria. A Linear Allocator (also called a Bump Allocator) is like a tall stack of clean trays.
- When you need memory, you take the top tray.
- The "top" of the stack moves down (or "bumps" forward).
- You don't wash trays one by one. When the meal is over, you take the entire used stack and wash them all at once, resetting the stack to the top.
In code, this is just a large array and a single integer (an offset or pointer) that tracks how many bytes you've used. To "allocate," you simply move that pointer forward.
A Simple Implementation
Here is how a basic Arena-based bump allocator looks in C:
#include <stdint.h>
#include <stddef.h>
typedef struct {
size_t size;
size_t offset;
uint8_t *buffer;
} Arena;
// To "allocate," we just slide the offset forward
void* arena_alloc(Arena *a, size_t bytes) {
// Check if we have enough room left
if (a->offset + bytes <= a->size) {
void *ptr = &a->buffer[a->offset];
a->offset += bytes; // The "Bump"
return ptr;
}
return NULL; // Out of memory
}
// To "free," we just reset the offset to zero
void arena_reset(Arena *a) {
a->offset = 0;
}
Why use this?
The main advantage is speed. There is no searching for gaps; it is just one addition operation. Secondly, it simplifies cleanup. If you are writing a game or a web request handler, you can allocate everything you need for one frame or one request, then call arena_reset() at the end. You don't have to worry about individual free() calls or memory leaks because the entire block is wiped clean in one go.
Key takeaway
A linear allocator is the fastest way to manage memory by "bumping" a pointer forward for every new object and clearing the entire pool at once.