TExcelTAD
Home › Game Engine Architecture in C++ › Pool Allocators

Pool Allocators

A pool allocator hands out fixed-size blocks from a preallocated array. Bullets, particles, sound voices, physics contacts, network packets and nodes of a tree are created and destroyed constantly, at unpredictable times, but they all have the same size. A pool makes both operations O(1), never fragments, and never touches the general-purpose heap during gameplay.

Allocator Allocate Free Order of frees Best for
Linear (arena) bump a pointer all at once none per-frame scratch data
Stack bump a pointer roll back to a marker LIFO level and loading lifetimes
Pool pop the free list push onto the free list any many same-sized objects
General heap search for a fitting block coalesce neighbors any everything else

The free list lives inside the free blocks

The trick that makes pools cheap: a free block isn't being used for anything, so it can store the index (or pointer) of the next free block. The pool needs no extra bookkeeping memory: one head variable is the whole free list.

text
blocks:   [0: next=1] [1: next=2] [2: next=3] [3: next=-1]      head = 0
alloc  -> returns 0, head = 1
alloc  -> returns 1, head = 2
free 0 -> block 0 stores next=2, head = 0
alloc  -> returns 0 again (most recently freed: still warm in the cache)
cpp · try it yourself
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>

class PoolAllocator {
    std::byte* memory_;
    std::size_t blockSize_, count_;
    std::int32_t head_ = 0;       // index of the first free block, -1 when empty
    std::size_t live_ = 0;
public:
    // blockSize must hold an int32 and be a multiple of the alignment the objects need
    PoolAllocator(std::byte* mem, std::size_t blockSize, std::size_t count)
        : memory_(mem), blockSize_(blockSize), count_(count) {
        for (std::size_t i = 0; i < count; i++) {
            std::int32_t next = i + 1 < count ? std::int32_t(i + 1) : -1;
            std::memcpy(memory_ + i * blockSize_, &next, sizeof next);   // link block i -> i+1
        }
    }
    void* allocate() {
        if (head_ < 0) return nullptr;                                   // pool exhausted
        std::byte* block = memory_ + std::size_t(head_) * blockSize_;
        std::memcpy(&head_, block, sizeof head_);                        // head = block.next
        live_++;
        return block;
    }
    void free(void* p) {
        auto index = std::int32_t((static_cast<std::byte*>(p) - memory_) / blockSize_);
        std::memcpy(p, &head_, sizeof head_);                            // block.next = head
        head_ = index;
        live_--;
    }
    std::size_t indexOf(const void* p) const { return (static_cast<const std::byte*>(p) - memory_) / blockSize_; }
    std::size_t live() const { return live_; }
};

struct Bullet { float x, y, vx, vy; int owner; };

int main() {
    constexpr std::size_t kBlock = (sizeof(Bullet) + alignof(Bullet) - 1) / alignof(Bullet) * alignof(Bullet);
    alignas(Bullet) static std::byte storage[kBlock * 4];
    PoolAllocator pool(storage, kBlock, 4);
    std::printf("block size %zu bytes, capacity 4\n", kBlock);

    void* a = pool.allocate();
    void* b = pool.allocate();
    void* c = pool.allocate();
    std::printf("allocated blocks %zu %zu %zu\n", pool.indexOf(a), pool.indexOf(b), pool.indexOf(c));
    pool.free(a);
    pool.free(c);
    void* d = pool.allocate();
    void* e = pool.allocate();
    std::printf("after freeing 0 and 2, new blocks: %zu %zu (last freed comes back first)\n",
                pool.indexOf(d), pool.indexOf(e));
    void* f = pool.allocate();
    void* g = pool.allocate();
    std::printf("next: %zu, then %s, live=%zu\n", pool.indexOf(f), g ? "a block" : "nullptr (full)", pool.live());
}
block size 20 bytes, capacity 4
allocated blocks 0 1 2
after freeing 0 and 2, new blocks: 2 0 (last freed comes back first)
next: 3, then nullptr (full), live=4

The pool returns blocks in LIFO order, so the block freed most recently (likely still in the CPU cache) is reused first. When the pool is full, allocate() returns nullptr and the caller decides: drop the oldest particle, skip spawning a decal, or grow by adding another pool page.

Note: Writing the next index with std::memcpy instead of casting the block to int32_t* sidesteps C++'s strict aliasing rules; the compiler turns it into a single store.

A typed object pool with safety checks

Raw blocks are easy to misuse: freeing twice corrupts the free list (the same block appears twice and two objects end up sharing memory), and forgetting the destructor leaks resources. A typed wrapper constructs and destroys objects, and a debug bitmap catches double frees:

cpp · try it yourself
#include <cstdio>
#include <new>
#include <string>
#include <utility>
#include <vector>

template <class T, std::size_t N>
class ObjectPool {
    union Slot {                       // either a live T or the next-free index
        T object;
        int nextFree;
        Slot() : nextFree(-1) {}
        ~Slot() {}
    };
    Slot slots_[N];
    bool inUse_[N] = {};               // debug bookkeeping
    int head_ = 0;
public:
    ObjectPool() { for (std::size_t i = 0; i < N; i++) slots_[i].nextFree = i + 1 < N ? int(i + 1) : -1; }
    ~ObjectPool() { for (std::size_t i = 0; i < N; i++) if (inUse_[i]) slots_[i].object.~T(); }

    template <class... Args> T* create(Args&&... args) {
        if (head_ < 0) return nullptr;
        int i = head_;
        head_ = slots_[i].nextFree;
        T* obj = new (&slots_[i].object) T(std::forward<Args>(args)...);
        inUse_[i] = true;
        return obj;
    }
    bool destroy(T* obj) {
        int i = int(reinterpret_cast<Slot*>(obj) - slots_);
        if (i < 0 || i >= int(N) || !inUse_[i]) {
            std::printf("  pool error: double free or foreign pointer (slot %d)\n", i);
            return false;
        }
        obj->~T();
        inUse_[i] = false;
        slots_[i].nextFree = head_;
        head_ = i;
        return true;
    }
    int slotOf(const T* obj) const { return int(reinterpret_cast<const Slot*>(obj) - slots_); }
};

struct Voice {
    std::string clip;
    float volume;
    Voice(std::string c, float v) : clip(std::move(c)), volume(v) { std::printf("  start %s\n", clip.c_str()); }
    ~Voice() { std::printf("  stop  %s\n", clip.c_str()); }
};

int main() {
    ObjectPool<Voice, 3> voices;
    Voice* a = voices.create("explosion.wav", 1.0f);
    Voice* b = voices.create("footstep.wav", 0.4f);
    std::printf("slots: %d %d\n", voices.slotOf(a), voices.slotOf(b));
    voices.destroy(a);
    voices.destroy(a);                         // bug caught in debug builds
    Voice* c = voices.create("music.ogg", 0.7f);
    std::printf("music reuses slot %d\n", voices.slotOf(c));
    std::puts("pool goes out of scope:");
}
  start explosion.wav
  start footstep.wav
slots: 0 1
  stop  explosion.wav
  pool error: double free or foreign pointer (slot 0)
  start music.ogg
music reuses slot 0
pool goes out of scope:
  stop  music.ogg
  stop  footstep.wav

The pool's destructor stops the voices that are still alive, so even a pool owns its contents properly.

Pools in practice

  • Size from data. Record the peak number of live objects per pool during playtests and set capacities with headroom. Log a warning the first time a pool overflows in a development build.
  • Pools and handles. Pool slots are a perfect home for objects referred to by generational handles: the handle stores the slot index plus a generation counter, so a stale handle to a reused slot is detected.
  • Iteration. A pool with holes is slow to iterate over (you visit dead slots). If you mostly iterate, prefer a densely packed array with swap-and-pop removal, which is what ECS component storage does; see A Sparse-Set ECS.
  • Threads. A pool shared between threads needs a lock or a lock-free free list (watch out for the ABA problem). Often simpler: one pool per thread, or allocate only on the main thread.
  • Size classes. A general-purpose small-object allocator is just a set of pools for sizes 16, 32, 48, 64… bytes, which is how most modern malloc implementations handle small requests.

Test yourself

Where does a pool allocator keep its free list?

  1. In a separate std::vector
  2. Inside the free blocks themselves, each storing the next free index
  3. In the operating system
  4. In a hash map from address to size

What happens if the same block is freed twice in a raw pool without checks?

  1. Nothing
  2. The block appears twice in the free list and two later allocations share the same memory
  3. The pool grows
  4. The program always crashes immediately

Which workload fits a pool allocator best?

  1. One large texture loaded at startup
  2. Thousands of same-sized projectiles created and destroyed in any order
  3. Temporary data freed together at the end of each frame
  4. Strings of varying lengths