KatInterview

Building a Slab Pool for Uniform Objects with Alignment Safety

Data Structure DesignModel answer
MediumModel answerData Structure Designmemory-allocatorslabfree-list

Last 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:

  1. How a slab is laid out, how the slot stride is chosen, and how the free list is threaded through unused slots.
  2. How allocation and deallocation work, and how the pool grows when it runs out of slots.
  3. How you guarantee that every returned pointer satisfies the requested alignment.
  4. How raw storage is kept separate from object lifetime (construction and destruction), and how this relates to new/delete and placement construction.
  5. What you do to detect or mitigate invalid frees, double frees, and memory corruption.
  6. Your choices for thread safety.
  7. 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.