Building a Slab Pool for Uniform Objects with Alignment Safety
Data Structure DesignModel answerLast updated
Design a pool allocator that carves equal-sized slots from slabs, hands them out via an intrusive free list in O(1), respects alignment, and packs 9-byte payloads sensibly.
You are asked to design a pool allocator for objects that all share one size. Storage comes from large blocks ("slabs") obtained from the system, and each slab is divided into equal slots. Unused slots are chained together in a linked list so they can be reused quickly.
Describe your design and cover the following:
- How a slab is laid out, how the slot stride is chosen, and how the free list is threaded through unused slots.
- How allocation and deallocation work, and how the pool grows when it runs out of slots.
- How you guarantee that every returned pointer satisfies the requested alignment.
- How raw storage is kept separate from object lifetime (construction and destruction), and how this relates to
new/deleteand placement construction. - What you do to detect or mitigate invalid frees, double frees, and memory corruption.
- Your choices for thread safety.
- How you would store objects whose payload is exactly 9 bytes without wasting memory needlessly.
Assumptions
- Every slot within one pool has the same stride.
- Allocate and free must be constant time in the common case.
- The allocator hands out raw storage only; constructing and destroying objects are separate steps.
- No returned pointer may violate the requested alignment.
Questions worth raising before you start
- What is the largest alignment you must support, and how many live allocations are expected?
- May completely empty slabs be returned to the operating system?
- Will one thread or many use the pool?
Hints
Hint 1
Distinguish the payload size (what the caller asked for) from the stride (the distance between consecutive slots). The stride must be at least as large as a free-list pointer and a multiple of the alignment.
Hint 2
An unused slot has no live object, so its own bytes can hold the 'next free' pointer. Think about what that means for the minimum slot size and for how freed memory could be poisoned.
Hint 3
For the 9-byte case, compare four options: pad to 16, lower the alignment to 1 and pack to 12 or 9 bytes, use a different size class, or store the payload in a structure-of-arrays layout. Consider the cost of misaligned access and the 8-byte free-list pointer.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core design
Pool state: a head pointer to the free list, a list of slabs (for bulk release), the stride, the alignment, and the number of slots per slab.
Stride. Compute stride = roundUp(max(payload, sizeof(void*)), align). The max is needed because a free slot must be able to hold the next pointer. Rounding up to align ensures that if slot 0 is aligned, every slot is.
Slab. Request a block of slotsPerSlab * stride bytes (plus a small header if you want slab links), with the base aligned to at least align. Use aligned_alloc, posix_memalign, or over-allocate and round the first slot address up manually. A header, if present, must be padded so the first slot stays aligned. A typical slab is 4 KiB to 64 KiB, or it can grow geometrically.
Free list. When a slab arrives, thread every slot into the list by writing the address of the next slot into the first bytes of each slot. This costs O(slots) once per slab; an alternative is a bump pointer inside the newest slab, which makes growth lazy and O(1) per allocation.
Operations
Allocate:
- If the free list is non-empty, pop the head:
p = head; head = *(void**)p. - Otherwise, bump-allocate from the current slab if space remains, or request a new slab and link it in.
- Return
p(raw, uninitialised memory).
Free: push the slot: *(void**)p = head; head = p. Both are a few instructions, so O(1). Growth is amortised O(1) per allocation. Freed slots are reused LIFO, which is cache-friendly.
Alignment
- Base of slab aligned to
align; stride a multiple ofalign; hence all slots aligned. - Validate that
alignis a power of two and that the stride is not smaller than the free-list pointer's own alignment (the pointer is stored inside the slot, so the slot must satisfyalignof(void*)or you must usememcpyto store it). - Common mistake: using
sizeof(T)as the stride without considering thatsizeofalready includes trailing padding, or forgetting over-aligned types (for example 64-byte cache-line alignment), whichmallocdoes not guarantee.
Lifetime
The allocator deals in raw bytes. The caller (or a typed wrapper) does:
- Construct:
T* t = new (pool.allocate()) T(args...)(placement new). - Destroy:
t->~T(); pool.deallocate(t);
Plain new T calls operator new then the constructor; delete t calls the destructor then operator delete. A pool can be plugged in by overloading operator new/operator delete for the class, but the allocator itself must never run constructors, since the same slot is reused for many objects over time. Also use std::launder when accessing an object through a pointer to reused storage if required by the language rules, and make sure the free-list pointer is written only after the destructor has finished.
Corruption defenses
- Ownership check on free: confirm the pointer lies within a known slab and that
(p - slabBase) % stride == 0. Slab lookup can use a small sorted array, or aligned slabs whereslabBase = p & ~(slabSize-1)gives O(1) lookup. - Double free: in debug builds keep a per-slot bit or state byte (allocated/free), or walk the list. A cheap trick is to write a magic value after the next pointer on free and check that it is absent on free (and present in free slots on allocation).
- Poisoning: fill freed slots with a pattern such as
0xDDso use-after-free reads are obvious, and verify the pattern when popping to detect writes to freed memory. - Guard bytes (redzones) around slots catch overflows at the cost of a larger stride; useful in debug builds.
- Hardening: XOR/obfuscate the next pointer with a per-pool secret (safe-linking) so an attacker cannot easily forge list entries.
- Tools such as AddressSanitizer manual poisoning can mark free slots as inaccessible.
Thread safety
Options, from simplest to most scalable:
- Single-threaded pool, with one pool per thread. No synchronisation and the fastest path.
- Mutex or spinlock around head and slab growth. Simple, but contended under load.
- Lock-free stack (CAS on head). Beware the ABA problem: use a tagged pointer (pointer plus counter, double-width CAS) or hazard pointers. Memory reclamation of slabs is harder.
- Thread-local caches that refill and flush in batches from a shared central pool; this is the usual production approach, since the lock is taken once per batch rather than once per operation. Remote frees (an object freed by a thread other than its allocator) need a return queue or a central flush.
Returning empty slabs to the OS needs a per-slab used count and is incompatible with a simple global free list unless free lists are per slab; decide based on the answer to the clarifying question.
The 9-byte payload
Payload 9, with a pointer-sized free link, gives these options:
| Option | Stride | Notes |
|---|---|---|
| Natural alignment of 8 | 16 | Simple, aligned, wastes 7 bytes (44%). Min stride covers the 8-byte link. |
| Alignment 1, packed | 9 would be too small for the link, so 16 or a 12-byte compromise is not possible without alignment loss; a 9-byte stride only works if free-list links are stored as indices | Misaligned loads on some CPUs are slow or fault; atomics on misaligned data are unsafe. |
| Index-based free list | 9 | Store a 4-byte slot index (not a pointer) in the free slot. Stride 9 now fits, objects have alignment 1, and a 9-byte stride in a slab with 32-bit indices addresses billions of slots. Access cost: bytes only, no aligned multi-byte fields. |
| Structure of arrays | 8 + 1 | Split the payload into an 8-byte field array and a 1-byte field array. Both fully aligned and 9 bytes per object; the handle is an index. |
| Different size class | 16 | Share a 16-byte class with other small types to cut fragmentation across pools. |
Recommendation: if the 9 bytes is a plain byte blob with alignment 1, use an index-based free list with stride 9 (or 12 if you want 4-byte-aligned index writes via memcpy). If it contains an 8-byte field plus a flag, use the structure-of-arrays layout, or accept 16 bytes. Always state the trade-off: memory saved versus speed, portability, and atomic safety. For 1 million objects, stride 16 costs 16 MB and stride 9 costs 9 MB, a 7 MB saving.
Common mistakes
- Stride smaller than the free-link, corrupting data.
- Ignoring alignment of the slab base.
- Running constructors or destructors inside the allocator.
- Lock-free pop without ABA protection.
- Not distinguishing "size requested" from "stride used".
- Accepting any pointer in
freewithout validation.