How does a circular (ring) buffer work?
Short answer: A ring buffer is a fixed-size array with a head (write) index and a tail (read) index that wrap around to the start when they reach the end. Writes advance the head, reads advance the tail, and both operations are O(1) with no dynamic memory. It is the standard structure for UART receive buffers, logging, audio and producer/consumer queues. With a power-of-two size, wrapping is a cheap bit mask, and free-running counters distinguish full from empty without wasting a slot.
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#define RB_SIZE 8u /* power of two */
static uint8_t buf[RB_SIZE];
static uint32_t head, tail; /* free-running: only ever incremented */
static uint32_t rb_count(void) { return head - tail; } /* unsigned wrap is fine */
bool rb_put(uint8_t b)
{
if (rb_count() == RB_SIZE) return false; /* full */
buf[head & (RB_SIZE - 1)] = b;
head++;
return true;
}
bool rb_get(uint8_t *b)
{
if (rb_count() == 0) return false; /* empty */
*b = buf[tail & (RB_SIZE - 1)];
tail++;
return true;
}
int main(void)
{
for (uint8_t i = 0; i < 10; i++) printf("%d", rb_put(i)); /* 1111111100 */
uint8_t v;
printf("\n");
while (rb_get(&v)) printf("%u ", v); /* 0 1 2 3 4 5 6 7 */
printf("\n");
return 0;
}
Ways to tell full from empty
| Method | Cost |
|---|---|
| Free-running counters (above) | none; needs power-of-two size |
Keep one slot empty ((head + 1) % N == tail means full) |
wastes one element |
Separate count variable |
extra variable shared by both sides (harder lock-free) |
Overwrite vs reject when full: logging and "latest value" buffers often overwrite the oldest data (advance the tail too); command queues should reject and report so nothing is silently lost.
Follow-ups: making it safe between an ISR and a task (next question), DMA-driven circular buffers (the DMA controller writes the head; firmware reads the DMA counter to know where it is), and bulk read/write with memcpy handling the wrap in two chunks.