Linear and Stack Allocators
General-purpose new/malloc is a marvel of engineering, but it has to handle every size, every lifetime and every thread, so each call costs a search, maybe a lock, and sometimes a system call. A game knows much more about its allocations: most temporary data lives for exactly one frame, level data lives until the level unloads, and particles come in thousands of identical sizes. Custom allocators exploit that knowledge.
Note: Measure first. Modern allocators (the system ones, mimalloc, jemalloc) are fast. Custom allocators earn their place where a profiler shows allocation cost, fragmentation or lock contention, or where lifetimes are naturally grouped (per frame, per level). They also make memory budgets visible: "the frame allocator has 8 MB" is a number you can track.
Alignment
Every type has an alignment requirement (alignof(T)): a double usually wants an address divisible by 8, an SSE __m128 by 16, data shared between threads is often aligned to a 64-byte cache line. An allocator must round each allocation's start up to the requested alignment. For power-of-two alignments that is one line of bit math:
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <initializer_list>
constexpr std::size_t alignUp(std::size_t offset, std::size_t align) { // align must be a power of two
return (offset + align - 1) & ~(align - 1);
}
struct alignas(16) Vec4 { float x, y, z, w; };
int main() {
for (std::size_t off : {0, 1, 7, 8, 13, 16, 17})
std::printf("offset %2zu -> align 8: %2zu, align 16: %2zu\n", off, alignUp(off, 8), alignUp(off, 16));
std::printf("alignof(char)=%zu alignof(int)=%zu alignof(double)=%zu alignof(Vec4)=%zu\n",
alignof(char), alignof(int), alignof(double), alignof(Vec4));
std::printf("max_align_t: %zu\n", alignof(std::max_align_t));
}offset 0 -> align 8: 0, align 16: 0
offset 1 -> align 8: 8, align 16: 16
offset 7 -> align 8: 8, align 16: 16
offset 8 -> align 8: 8, align 16: 16
offset 13 -> align 8: 16, align 16: 16
offset 16 -> align 8: 16, align 16: 16
offset 17 -> align 8: 24, align 16: 32
alignof(char)=1 alignof(int)=4 alignof(double)=8 alignof(Vec4)=16
max_align_t: 16
align - 1 is a mask of the low bits; adding it and clearing those bits rounds up to the next multiple. If align isn't a power of two the trick silently gives wrong answers, so real allocators assert it: (align & (align - 1)) == 0.
The linear (bump, arena) allocator
The simplest and fastest allocator: a block of memory and an offset. Allocating rounds the offset up and bumps it. There is no individual free: the whole arena is reset at once. That fits a frame allocator perfectly: everything allocated for this frame's temporary work (visible-object lists, sorted draw keys, string formatting) is thrown away in one instruction at the start of the next frame.
#include <cstddef>
#include <cstdio>
#include <new>
constexpr std::size_t alignUp(std::size_t v, std::size_t a) { return (v + a - 1) & ~(a - 1); }
class LinearAllocator {
std::byte* base_;
std::size_t capacity_, offset_ = 0, peak_ = 0;
public:
LinearAllocator(std::byte* mem, std::size_t size) : base_(mem), capacity_(size) {}
void* allocate(std::size_t size, std::size_t align) {
std::size_t start = alignUp(offset_, align);
if (start + size > capacity_) return nullptr; // out of budget: caller decides
offset_ = start + size;
if (offset_ > peak_) peak_ = offset_;
return base_ + start;
}
template <class T, class... Args> T* make(Args&&... args) {
void* p = allocate(sizeof(T), alignof(T));
return p ? new (p) T(static_cast<Args&&>(args)...) : nullptr; // placement new
}
std::size_t offsetOf(const void* p) const { return static_cast<const std::byte*>(p) - base_; }
void reset() { offset_ = 0; } // "free" everything at once
std::size_t used() const { return offset_; }
std::size_t peak() const { return peak_; }
};
struct Particle { float x, y, vx, vy; };
struct alignas(16) Matrix { float m[16]; };
int main() {
alignas(64) static std::byte frameMemory[256];
LinearAllocator frame(frameMemory, sizeof frameMemory);
for (int f = 0; f < 2; f++) {
frame.reset();
char* label = static_cast<char*>(frame.allocate(5, 1));
Particle* p = frame.make<Particle>(1.0f, 2.0f, 0.0f, 0.0f);
Matrix* m = frame.make<Matrix>();
std::printf("frame %d: label@%zu particle@%zu matrix@%zu used=%zu\n", f, frame.offsetOf(label),
frame.offsetOf(p), frame.offsetOf(m), frame.used());
int count = 0;
while (frame.make<Matrix>()) count++; // fill until the budget runs out
std::printf(" %d more matrices fit, then allocate() returned nullptr\n", count);
}
std::printf("peak usage: %zu of %zu bytes\n", frame.peak(), sizeof frameMemory);
}frame 0: label@0 particle@8 matrix@32 used=96
2 more matrices fit, then allocate() returned nullptr
frame 1: label@0 particle@8 matrix@32 used=96
2 more matrices fit, then allocate() returned nullptr
peak usage: 224 of 256 bytes
The Particle starts at offset 8 (not 5) because a float struct needs 4-byte alignment and the matrix at 32 because it asked for 16. Note what is missing: no destructors run on reset(). A linear allocator is for trivially destructible data (plain structs, arrays of numbers), or for objects whose destructors you call yourself.
Tip: Fill freed arena memory with a pattern such as
0xCDin debug builds. A use-after-reset bug then reads obvious garbage instead of last frame's plausible data.
The stack allocator
A stack allocator is a linear allocator that can also roll back to a marker. Loading a level is a natural fit: take a marker, allocate the level's data, and when the level unloads, free back to the marker. Nested lifetimes (level → room → temporary loading buffers) become nested markers.
#include <cstddef>
#include <cstdio>
constexpr std::size_t alignUp(std::size_t v, std::size_t a) { return (v + a - 1) & ~(a - 1); }
class StackAllocator {
std::byte* base_;
std::size_t capacity_, top_ = 0;
public:
using Marker = std::size_t;
StackAllocator(std::byte* mem, std::size_t size) : base_(mem), capacity_(size) {}
void* allocate(std::size_t size, std::size_t align = alignof(std::max_align_t)) {
std::size_t start = alignUp(top_, align);
if (start + size > capacity_) return nullptr;
top_ = start + size;
return base_ + start;
}
Marker mark() const { return top_; }
void freeTo(Marker m) { top_ = m; } // releases everything allocated after the marker
std::size_t used() const { return top_; }
};
int main() {
alignas(64) static std::byte memory[64 * 1024];
StackAllocator stack(memory, sizeof memory);
stack.allocate(4096); // engine-lifetime data
std::printf("engine data loaded: used %5zu\n", stack.used());
auto levelStart = stack.mark();
stack.allocate(20000); // level geometry
std::printf("level loaded: used %5zu\n", stack.used());
auto roomStart = stack.mark();
stack.allocate(6000); // room A props
std::printf("room A loaded: used %5zu\n", stack.used());
stack.freeTo(roomStart);
stack.allocate(9000); // room B props, reuses room A's space
std::printf("room A -> room B: used %5zu\n", stack.used());
stack.freeTo(levelStart);
std::printf("level unloaded: used %5zu\n", stack.used());
}engine data loaded: used 4096
level loaded: used 24096
room A loaded: used 30096
room A -> room B: used 33096
level unloaded: used 4096
The rule is strict last-in, first-out. Freeing the level while forgetting that room B was allocated after it frees room B too, which is usually what you want, but freeing room A's marker while the level marker is older is a bug. Debug builds catch it by keeping the markers on a small stack and asserting order.
A common variant is the double-ended stack: long-lived data grows from the bottom, temporary loading data from the top, and they fail only when they meet in the middle.
The standard-library version: std::pmr
Since C++17 the standard library has polymorphic memory resources. std::pmr::monotonic_buffer_resource is a linear allocator, and std::pmr::vector, std::pmr::string and friends can use it. This program counts how often the arena had to go to the upstream (general) allocator:
#include <cstddef>
#include <cstdio>
#include <memory_resource>
#include <vector>
struct CountingResource : std::pmr::memory_resource { // wraps new/delete and counts calls
int allocations = 0;
void* do_allocate(std::size_t bytes, std::size_t align) override {
allocations++;
return std::pmr::new_delete_resource()->allocate(bytes, align);
}
void do_deallocate(void* p, std::size_t bytes, std::size_t align) override {
std::pmr::new_delete_resource()->deallocate(p, bytes, align);
}
bool do_is_equal(const std::pmr::memory_resource& o) const noexcept override { return this == &o; }
};
int main() {
CountingResource heap;
for (int frame = 0; frame < 3; frame++) {
alignas(64) std::byte buffer[4096];
std::pmr::monotonic_buffer_resource arena(buffer, sizeof buffer, &heap);
std::pmr::vector<int> visible(&arena);
for (int i = 0; i < 300; i++) visible.push_back(i); // grows by reallocating inside the arena
std::printf("frame %d: %zu visible objects, heap calls so far: %d\n", frame, visible.size(),
heap.allocations);
} // arena destroyed: everything released at once
alignas(64) std::byte small[256];
std::pmr::monotonic_buffer_resource arena(small, sizeof small, &heap);
std::pmr::vector<int> big(&arena);
for (int i = 0; i < 300; i++) big.push_back(i);
std::printf("256-byte buffer: heap calls so far: %d (overflow went upstream)\n", heap.allocations);
}frame 0: 300 visible objects, heap calls so far: 0
frame 1: 300 visible objects, heap calls so far: 0
frame 2: 300 visible objects, heap calls so far: 0
256-byte buffer: heap calls so far: 4 (overflow went upstream)
With a 4 KB buffer the vector's growth never touches the heap. With 256 bytes, the arena overflows and asks its upstream resource for more blocks, which is how a frame allocator can degrade gracefully instead of failing.
Test yourself
What does alignUp(13, 8) return?
- 8
- 13
- 16
- 21
Why is a linear allocator a good fit for per-frame temporary data?
- It frees each object individually very fast
- Everything allocated in a frame dies together, so one reset frees it all
- It is thread-safe without locks
- It runs destructors automatically
What can a stack allocator do that a linear allocator cannot?
- Free individual objects in any order
- Roll back to a saved marker, freeing everything allocated after it
- Grow without limit
- Allocate without alignment