Circular Buffer
A circular buffer is a fixed array used as a queue by wrapping indices at the capacity. Head and tail chase each other around the ring. When they meet, the buffer is empty or full, and you need a rule to tell which.
Detailed Explanation
Audio, serial ports, kernel pipes, and lock-free single-producer queues all use this shape. You allocate cap slots once. head is the next index to read. tail is the next index to write. Advance with i = (i + 1) % cap. If cap is a power of two, i = (i + 1) & (cap - 1) is the same wrap without a divide.
Empty is head == tail. Full cannot also be head == tail unless you store extra state. Three ways out:
- Keep a
len. Full islen == cap. Empty islen == 0. Indices can be equal in both cases;lendecides. - Waste one slot. Full is
(tail + 1) % cap == head. You store at mostcap - 1items. - Keep a boolean
fullflag, set when a write makestail == head.
Option 1 is the most readable. Option 2 is common in hardware and in some lock-free rings. Pick one and test both the empty and the full transitions.
A circular buffer is bounded by construction. A write into a full buffer is a policy: reject, overwrite the oldest, or block. Overwriting without moving head corrupts the queue. Overwriting and advancing head is a lossy stream, which is correct for a telemetry sampler and wrong for bytes you must not drop.
The buffer owns its storage if you malloc'd it. It does not own pointees if the slots are pointers. Reset is setting head = tail = 0 and len = 0; it does not free the array unless you are destroying the object.
Thread safety is not included. One reader and one writer can share a ring with atomics and careful memory order; two writers cannot without a lock. Start with a mutex around the whole buffer unless you have measured the need for a lock-free design.
Code Examples
#include <stdio.h>
#include <stdlib.h>
struct Ring {
int *data;
size_t cap;
size_t head;
size_t len;
};
static int ring_push(struct Ring *r, int value)
{
if (r->len == r->cap) {
return -1; /* full: caller decides what to do */
}
size_t tail = (r->head + r->len) % r->cap;
r->data[tail] = value;
r->len++;
return 0;
}
static int ring_pop(struct Ring *r, int *out)
{
if (r->len == 0) {
return -1;
}
*out = r->data[r->head];
r->head = (r->head + 1) % r->cap;
r->len--;
return 0;
}
int main(void)
{
int storage[3];
struct Ring r = { storage, 3, 0, 0 };
ring_push(&r, 1);
ring_push(&r, 2);
ring_push(&r, 3);
int v;
ring_pop(&r, &v);
ring_push(&r, 4); /* reuses the slot 1 left */
ring_pop(&r, &v);
printf("%d\n", v); /* prints: 2 */
return 0;
}Common Gotchas
Using `head == tail` for both empty and full without a count or wasted slot makes the two states identical
the next pop or push will be wrong.
`% cap` with `cap == 0` is undefined behavior
a zero-capacity ring should be rejected in `init`.
Overwriting a full ring without advancing `head` duplicates or loses the wrong item
define the overflow policy in the function name (`try_push` vs `overwrite`).
Power-of-two capacity lets you mask instead of divide
that is a speed trick, not a correctness requirement.