DEV Community

yurtrimu
yurtrimu

Posted on

Why I built a simple C object pool (C89, O(1) allocation, no malloc churn)

Dynamic memory allocation in C is flexible, but it becomes a bottleneck in systems where objects are created and destroyed frequently. Repeated malloc/free calls can introduce overhead, fragmentation, and unpredictable latency.

To avoid that, I built a small object pool in C89.

The idea is simple: instead of allocating and freeing objects continuously, you allocate a fixed block of memory once at initialization. After that, objects are reused from that block.

Allocation and deallocation become constant time operations (O(1)), since the pool just tracks free slots internally.

Core behavior:

A fixed number of objects are preallocated
Objects are reused instead of freed back to the heap
No repeated heap allocation after initialization
Predictable performance characteristics

This pattern is commonly used in:

Game engines (particles, entities, bullets)
Networking systems (packet buffers)
Embedded systems with constrained or deterministic memory requirements
Real-time systems where allocation jitter is unacceptable

The API is intentionally minimal: a simple push/pop model where you “take” an object from the pool, use it, and return it when done.

Conceptually:

pop → get an object from the pool
use it
push → return it to the pool

This avoids fragmentation because memory is never returned to the general heap during normal operation. Instead, reuse is managed internally.

Tradeoff:
The main limitation is fixed capacity. If the pool is full, allocation fails or must be handled explicitly depending on configuration. This is a deliberate constraint to guarantee predictable behavior.

The implementation is kept C89-compatible and dependency-free so it can be dropped into low-level projects without modification.

Repository:
https://github.com/xyurt/object-pool

Top comments (0)