Home / Learn Embedded C / Circular Buffers in Memory

Circular Buffers in Memory

A fixed-size buffer that wraps around — the workhorse data structure of embedded communication.

In shortA fixed-size buffer that wraps around — the workhorse data structure of embedded communication.

What's actually going on

A circular buffer's wrap-aroundwrite to index 0write to index 1... continue tothe last index ...wrap back to index0 again
A circular buffer's wrap-around

In plain terms

A circular (ring) buffer is a fixed-size array with a read index and a write index that both wrap back to zero after reaching the end, letting producers and consumers run at different speeds without reallocating memory.

Why we use it

UART receive buffers, sensor history logs and audio buffers all need to accept new data continuously without ever growing unbounded — a circular buffer handles this with fixed, predictable memory usage.

Under the hood

Writing advances the write index (mod the buffer size); reading advances the read index the same way; the buffer is empty when both indices match, and full when the write index is about to catch up to the read index.

Real-world use

  • UART receive buffers
  • Sensor history logs
  • Audio/streaming buffers

Try it

A small circular buffer, wrapping aroundC: edit and run

Notice slot 0 and 1 get written to twice — the 5th and 6th values overwrite the 1st and 2nd, exactly as a ring buffer is meant to behave.

Careful:A naive circular buffer cannot distinguish "completely empty" from "completely full" using only read/write indices that are equal — real implementations track a count, or always leave one slot deliberately unused, to resolve this.

Try it: reading and writing with separate indices

A circular buffer with independent read and write indicesC: edit and run

Tracking count alongside the two indices is exactly how real ring-buffer drivers tell "empty" and "full" apart.

Quick quiz

1. Why is a circular buffer's memory usage fixed no matter how long a device runs?