Ring Buffer (C)
Topics: ring buffer, FIFO queue, fixed-capacity, no allocation
Problem
Implement a fixed-capacity FIFO ring buffer over caller-provided storage (no malloc) — the
classic bounded queue used in audio/IO buffers, lock-free pipes, and embedded firmware.
typedef struct { int *buf; size_t cap; size_t head; size_t count; } RingBuffer;
void rb_init(RingBuffer *rb, int *storage, size_t cap);
bool rb_push(RingBuffer *rb, int x); // false if full
bool rb_pop(RingBuffer *rb, int *out); // false if empty; writes the oldest value
size_t rb_len(const RingBuffer *rb);
bool rb_is_empty(const RingBuffer *rb);
bool rb_is_full(const RingBuffer *rb);
rb_init points the buffer at storage (room for cap ints).
rb_push appends; fails (returns false) when full.
rb_pop removes the oldest element (FIFO) into *out; fails when empty.
- Indices wrap around the array, so the buffer keeps working as it fills and drains.
init(cap 3); push 1,2,3 (full); pop -> 1; push 4 (wraps); pop,pop -> 2,3,4
Key concepts
- Track head + count: keep the next-write index and the element count; derive the read index as
(head + cap - count) % cap. (Avoids the "empty vs full look identical" ambiguity of a head/tail
pair.)
- Modular arithmetic advances indices around the fixed array — that's the "ring."
- No allocation: the caller owns the storage, so the buffer is usable on the stack or in
fixed-memory environments.
Run
cc -std=c11 -O2 -Wall tests.c -o /tmp/rb && /tmp/rb # tests.c #includes ringbuffer.c
Sign in to submit your solution.