ArticleslgStudy

computer science

Circular buffer

Circular buffer is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Circular buffer rather than just read about it. In short: In computer science, a circular buffer, circular queue, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. This structure lends itself easily to buffering data streams.

Circular buffer — main illustration
Circular buffer — illustration

Key takeaways

  • Circular buffer belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Circular buffer to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Circular buffer from memory before moving on to harder problems.

Reference excerpt

In computer science, a circular buffer, circular queue, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. This structure lends itself easily to buffering data streams. There were early circular buffer implementations in hardware.

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:

Uses The useful property of a circular buffer is that it does not need to have its elements shuffled around when one is consumed. (If a non-circular buffer were used then it would be necessary to shift all elements when one is consumed.) In other words, the circular buffer is well-suited as a FIFO (first in, first out) buffer while a standard, non-circular buffer is well suited as a LIFO (last in, first out) buffer. Circular buffering makes a good implementation strategy for a queue that has fixed maximum size. Should a maximum size be adopted for a queue, then a circular buffer is a completely ideal implementation; all queue operations are constant time. However, expanding a circular buffer requires shifting memory, which is comparatively costly. For arbitrarily expanding queues, a linked list approach may be preferred instead. In some situations, an overwriting circular buffer can be used, e.g. in multimedia. If the buffer is used as the bounded buffer in the producer–consumer problem then it is probably desired for the producer (e.g., an audio generator) to overwrite old data if the consumer (e.g., the sound card) is unable to momentarily keep up. Also, the LZ77 family of lossless data compression algorithms operates on the assumption that strings seen more recently in a data stream are more likely to occur soon in the stream. Implementations store the most recent data in a circular buffer.

Circular buffer mechanics

A circular buffer can be implemented using a pointer and four integers:

buffer start in memory buffer capacity (length) "write to" buffer index (end) "read from" buffer index (start) This image shows a partially full buffer with Length = 7:

This image shows a full buffer with four elements (numbers 1 through 4) having been overwritten:

In the beginning the indexes end and start are set to 0. The circular buffer write operation writes an element to the end index position and the end index is incremented to the next buffer position. The circular buffer read operation reads an element from the start index position and the start index is incremented to the next buffer position. The start and end indexes alone are not enough to distinguish between buffer full or empty state while also utilizing all buffer slots, but can be if the buffer only has a maximum in-use size of Length − 1. In this case, the buffer is empty if the start and end indexes are equal and full when the in-use size is Length − 1. Another solution is to have another integer count that is incremented at a write operation and decremented at a read operation. Then checking for emptiness means testing count equals 0 and checking for fullness means testing count equals Length. The following source code is a minimal C++ implementation. push() puts an item in the buffer, pop() gets an item from the buffer. Both functions take care about the capacity of the buffer:

Optimization A circular-buffer implementation may be optimized by mapping the underlying buffer to two contiguous regions of virtual memory. (Naturally, the underlying buffer‘s length must then equal some multiple of the system’s page size.) Reading from and writing to the circular buffer may then be carried out with greater efficiency by means of direct memory access; those accesses which fall beyond the end of the first virtual-memory region will automatically wrap around to the beginning of the underlying buffer. When the read offset is advanced into the second virtual-memory region, both offsets—read and write—are decremented by the length of the underlying buffer.

Fixed-length-element and contiguous-block circular buffer Perhaps the most common version of the circular buffer uses 8-bit bytes as elements. Some implementations of the circular buffer use fixed-length elements that are bigger than 8-bit bytes—16-bit integers for audio buffers, 53-byte ATM cells for telecom buffers, etc. Each item is contiguous and has the correct data alignment, so software reading and writing these values can be faster than software that handles non-contiguous and non-aligned values. Ping-pong buffering can be considered a very specialized circular buffer with exactly two large fixed-length elements. The bip buffer (bipartite buffer) is very similar to a circular buffer, except it always returns contiguous blocks which can be variable length. This offers nearly all the efficiency advantages of a circular buffer while maintaining the ability for the buffer to be used in APIs that only accept contiguous blocks. Fixed-sized compressed circular buffers use an alternative indexing strategy based on elementary number theory to maintain a fixed-sized compressed representation of the entire data sequence.

References

… excerpt ends here. Continue reading the full article.

Illustrations

Circular buffer: A ring showing, conceptually, a circular buffer. This visually shows that the buffer has no real end and it can loop around the buffer. However, since memory is never physically created as a ring, a linear representation is generally used as is done below.
A ring showing, conceptually, a circular buffer. This visually shows that the buffer has no real end and it can loop around the buffer. However, since memory is never physically created as a ring, a linear representation is generally used as is done below.
Circular buffer: A 24-byte keyboard circular buffer. When the write pointer is about to reach the read pointer—because the microprocessor is not responding—the buffer stops recording keystrokes. On some computers a beep would be played.
A 24-byte keyboard circular buffer. When the write pointer is about to reach the read pointer—because the microprocessor is not responding—the buffer stops recording keystrokes. On some computers a beep would be played.
Circular buffer illustration
Circular buffer illustration
Circular buffer illustration

Worked examples

Example 1 — a first encounter with Circular buffer

Start with the simplest possible case. Write down what Circular buffer claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Circular buffer before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Circular buffer ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Circular buffer

In research
Circular buffer appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Circular buffer in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Circular buffer is common in secondary-school and first-year university syllabi. It links to neighbouring topics Arrays, Computer memory, so understanding it makes those chapters shorter.
In everyday life
Look for Circular buffer outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Circular buffer” →

How to study Circular buffer in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Circular buffer means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Circular buffer out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Circular buffer in simple terms?

In computer science, a circular buffer, circular queue, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end. This structure lends itself easily to buffering data streams.

Why does Circular buffer matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Circular buffer?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Circular buffer.

Tags

  • Arrays
  • Computer memory

Keep exploring