Lably
Skip to content

Circular buffer

Data structure in computer science

  • 9 min read
  • 5 chapters

Learn it on Lably

Overview

A circular buffer first starts out empty and has a set length. In the diagram below is a 7-element buffer:

Assume that 1 is written in the center of a circular buffer (the exact starting location is not important in a circular buffer):

Then assume that two more elements are added to the circular buffer — 2 & 3 — which get put after 1:

If two elements are removed, the two oldest values inside of the circular buffer would be removed. Circular buffers use FIFO (first in, first out) logic. In the example, 1 & 2 were the first to enter the circular buffer, they are the first to be removed, leaving 3 inside of the buffer. When elements get removed, only the read-pointer moves to the next element. Removed elements are still in the buffer, waiting to get overwritten by new elements.

If the buffer has 7 elements, then it is completely full:

A property of the circular buffer is that when it is full and a subsequent write is performed, then it starts overwriting the oldest data. In the current example, two more elements — A & B — are added and they overwrite the 3 & 4:

Alternatively, the routines that manage the buffer could prevent overwriting the data and return an error or raise an exception. Whether or not data is overwritten is up to the semantics of the buffer routines or the application using the circular buffer.

Finally, if two elements are now removed then what would be removed is not A & B, but 5 & 6 because 5 & 6 are now the oldest elements, yielding the buffer with:

Sign in to keep reading

4 more chapters are free with a Lably account.

More in Computing and communication