A circular buffer is a fixed array that writes at one end and reads at the other, with both indexes wrapping back to the start. Nothing is copied when it wraps, nothing is allocated after initialization, and the capacity is exactly the memory it holds. A power-of-two capacity turns the wrap into a bitwise AND: in the measured run, a push/pop pair cost 0.97 ns with the mask and 8.23 ns with %. The same structure hands data from one thread to another without a lock, and the C11 single-producer single-consumer version moved 86.77 million items per second against 9.33 million for a mutex-protected ring.
This guide treats the ring buffer as a systems technique in C and C++. It covers the mask, the full/empty ambiguity and its three fixes, the memory ordering behind a lock-free ring, cache-line separation of the indexes, and the measurements and sanitizer reports that back each claim. The FIFO data type itself belongs to the Queue article. Every program was compiled and tested on Ubuntu 24.04 with GCC 13.3 and Clang 18.1.3, and with MSVC 19.44 on Windows 11. The code is in the c-examples and cpp-examples repositories.
What Is a Circular Buffer?
A circular buffer, or ring buffer, is a fixed-size array used as a FIFO queue whose write and read positions wrap around the end back to the start. It keeps one index for the next write, one for the next read and a way to tell full from empty, so both ends run in constant time and the storage is never reallocated.
The structure solves a specific problem. A producer and a consumer run at different rates and need to hand data over without allocating, copying or blocking. A network driver receives packets into a ring before the protocol stack reads them. An audio callback writes samples into a ring that the sound card drains, and a logging thread hands lines to a writer the same way. The fixed capacity bounds the memory, and the wrap lets the buffer run forever, reusing the same slots in order.
There are two modes, and an implementation should document which one it uses. In the FIFO mode shown here, a push into a full buffer fails and a pop from an empty one fails, and the caller decides whether to drop, retry or block. In overwrite mode, a push into a full buffer replaces the oldest value, which is what a telemetry or flight-recorder ring wants because the latest data matters most. The wrap, the mask and the full/empty rules are the same in both modes. Only the branch taken on full changes.
A ring is not a growable array. A dynamic array grows and copies so that it never rejects a push, while a ring never grows and rejects the push instead. That trade is the point: hard memory bounds, predictable latency and no allocation in the hot path. The Arrays article covers the contiguous memory a ring is built from.
This article follows the naming of the Linux kernel’s circular buffer documentation: the producer inserts at the head and the consumer takes from the tail. Some queue tutorials use the opposite names, so check which index is which before you compare code.
How This Was Measured
| Setting | Value |
|---|---|
| Date tested | December 1, 2026 |
| Hardware | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300 |
| Operating system | Ubuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39, and Windows 11 for the MSVC build |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 through CMake Release, MSVC 19.44 at /W4 /WX |
| Indexing experiment | 100,000,000 push/pop pairs on a 1024-slot ring, once with mask indexing and once with modulo indexing, same data |
| Synchronization experiment | 20,000,000 items from one producer thread to one consumer thread, lock-free SPSC ring against a pthread-mutex ring, same data |
| Sanitizers | AddressSanitizer and UndefinedBehaviorSanitizer for the ring and the pitfalls, ThreadSanitizer for the SPSC tests and the non-atomic pitfall |
| What is timed | The push/pop loop, or the full producer-to-consumer run. Setup and verification are outside the timed regions |
| Statistic | One run of each configuration, no repetitions or median. Nanoseconds per pair and million items per second are derived from the measured time |
| Check | Each experiment verifies a checksum over the transferred values, and both variants in each experiment must agree |
No CPU pinning or frequency control was used, and the host was running other software, so the timings are indicative for this machine and the ratios are the useful part. The operating system schedules the producer and consumer threads, and scheduling affects both variants of the synchronization experiment equally.
The Wrap-Around: Mask Against Modulo
With a capacity of eight, the write index walks 0, 1, …, 7 and then must return to 0. The general expression is (index + 1) % capacity, and the power-of-two expression is (index + 1) & (capacity - 1). The two give the same result exactly when the capacity is a power of two, because the low bits of the index are then the slot number and the mask keeps them. The AND needs no division. Even on a CPU with a fast divider, the difference shows in a loop that does nothing else, and the measurement below isolates exactly that loop.
The power-of-two rule limits the capacity, not the data. A 1000-slot buffer becomes 1024 slots and wastes 24, which is usually a good trade. If the capacity must be arbitrary, the modulo form works and the mask form gives wrong answers. The implementation should make the rule impossible to miss. The C version validates the capacity at initialization, and the C++ version encodes it as a static_assert, so a non-power-of-two capacity is a compile error rather than a silent bug.
The second design choice is what the indexes mean. A wrapped index always stays in [0, capacity). A free-running counter only grows and is masked when it addresses the array, and the difference between head and tail is the number of stored items. Unsigned arithmetic in C and C++ is defined to wrap modulo 2^N, and a power-of-two capacity divides 2^N, so both the difference and the masked slot stay correct even when a counter passes SIZE_MAX. The lock-free ring in this article uses free-running counters for that reason.
Full, Empty and the Head/Tail Ambiguity
If the ring keeps only head and tail, the two are equal in the empty buffer and equal again in a full buffer, after the head has wrapped around to meet the tail. The two states cannot be told apart from the indexes alone. That is the bug in the first pitfall below: a full buffer reports empty, and the next push overwrites the oldest value.
There are three standard fixes:
- Keep a count of stored values and compare it with zero and with the capacity. This is the choice for the single-threaded ring here, and it costs one word and one increment or decrement per operation.
- Leave one slot unused, so the ring is full when
(head + 1) & mask == tail. This saves the counter but reduces the usable capacity by one. - Keep free-running counters and compare their difference with the capacity. The lock-free ring does this, because the difference is the count and each side writes only its own counter.
The Lock-Free SPSC Ring
One producer and one consumer can share a ring without a mutex because each side owns one index. The producer writes the next slot and then publishes its new head with a release store. The consumer acquire-loads the head, reads the slots up to it, and publishes its new tail with a release store. The producer acquire-loads the tail before deciding whether there is room. A release store makes every write that came before it visible to a thread whose acquire load reads the stored value, which is exactly the data-before-index publication the ring needs.
The counters are std::atomic<std::size_t> in C++ and _Atomic size_t in C. The two threads never write the same atomic: the producer writes head and reads tail, and the consumer writes tail and reads head. That single-writer property lets the design work with plain loads and stores, with no compare-and-swap and no read-modify-write. The mutex version is the control. It also works, and the measurement shows what the lock costs when the critical section is a few instructions.
Correctness has two halves. The data must be published before the index that announces it, and a slot must not be reused before the other side has finished with it. The release/acquire pair on head covers the first. The second comes from the consumer’s release store of tail, which the producer acquire-loads before it writes a slot the consumer may still be reading. The ThreadSanitizer test runs a million items through the ring on two threads and checks the sum, so a missing ordering shows up as a race report or a wrong checksum.
Cache Lines and False Sharing
Two atomics that sit next to each other in memory share a cache line. The producer updates head and the consumer updates tail on different cores. If the two values share a line, every write by one side invalidates that line in the other core’s cache even though the values are independent. That is false sharing. The fix is to place the two indexes on separate cache lines, usually 64 bytes apart on x86-64. The C struct uses _Alignas(64) on each counter, and the C++ class uses alignas(64) on both counters and on the slot array.
The data slots are shared by design, and that sharing is the real communication: the producer writes a slot the consumer has already freed, and the consumer reads a slot the producer has just filled. The indexes only announce how far the communication has progressed, so they should not bounce between cores on every operation.
The measurement does not isolate false sharing, because the slots in a small ring share lines too. The padding follows from the cache-line size and standard practice, so this article states it as a design rule rather than a measured result.
Circular Buffer Implementation in C
The C ring is a struct with a heap buffer, a mask, two wrapped indexes and a count. Initialization accepts only a nonzero power of two and stores capacity - 1 as the mask. Push and pop are a few statements with one mask each.
bool ring_init(Ring *ring, size_t capacity)
{
ring->data = NULL;
ring->capacity = 0;
ring->mask = 0;
ring->head = 0;
ring->tail = 0;
ring->size = 0;
if (!is_power_of_two(capacity))
return false;
if (capacity > SIZE_MAX / sizeof *ring->data)
return false;
ring->data = malloc(capacity * sizeof *ring->data);
if (ring->data == NULL)
return false;
ring->capacity = capacity;
ring->mask = capacity - 1;
return true;
}
bool ring_push(Ring *ring, int value)
{
if (ring->size == ring->capacity)
return false;
ring->data[ring->head] = value;
ring->head = (ring->head + 1) & ring->mask;
ring->size++;
return true;
}
/* Reads the oldest value into *value and advances tail. Returns false when the
* ring is empty and writes nothing then. */
bool ring_pop(Ring *ring, int *value)
{
if (ring->size == 0)
return false;
*value = ring->data[ring->tail];
ring->tail = (ring->tail + 1) & ring->mask;
ring->size--;
return true;
}
The lock-free ring lives in its own source file because it needs the atomic types and a different contract. The producer thread calls spsc_push, the consumer thread calls spsc_pop, and no other thread may touch either side. The head and tail are free-running counters, masked only when they index the slots.
bool spsc_push(SpscRing *ring, int value)
{
size_t head = atomic_load_explicit(&ring->head, memory_order_relaxed);
size_t tail = atomic_load_explicit(&ring->tail, memory_order_acquire);
if (head - tail >= ring->capacity)
return false;
ring->data[head & ring->mask] = value;
atomic_store_explicit(&ring->head, head + 1, memory_order_release);
return true;
}
/* Consumer side only. Reads the oldest value into *value unless the ring is
* empty. Returns false when empty and writes nothing then. */
bool spsc_pop(SpscRing *ring, int *value)
{
size_t tail = atomic_load_explicit(&ring->tail, memory_order_relaxed);
size_t head = atomic_load_explicit(&ring->head, memory_order_acquire);
if (tail == head)
return false;
*value = ring->data[tail & ring->mask];
atomic_store_explicit(&ring->tail, tail + 1, memory_order_release);
return true;
}
The demo in ring.c exercises the single-threaded ring with a capacity of four:
circular buffer, capacity 4, mask indexing
push 10, 20, 30 -> size 3, front 10, back 30
pop -> 10, size 2, front 20
push 40, 50 -> size 4, full true
push 60 -> rejected, size 4, front 20
pop -> 20, size 3, front 30
push 60 -> size 4, back 60
pop all: 30 40 50 60 -> size 0, empty true
Circular Buffer Implementation in C++
The C++ version is two header-only templates. RingBuffer<T, Capacity> is the single-threaded ring, with a static_assert that the capacity is a power of two, a std::array buffer and std::optional for an absent value. SpscRing<T, Capacity> is the lock-free ring, with std::atomic counters on separate cache lines.
bool push(const T& value)
{
if (full())
return false;
slots_[mask(head_)] = value;
head_ = next(head_);
++count_;
return true;
}
bool push(T&& value)
{
if (full())
return false;
slots_[mask(head_)] = std::move(value);
head_ = next(head_);
++count_;
return true;
}
// Removes and returns the oldest value, or std::nullopt when the ring is
// empty.
[[nodiscard]] std::optional<T> pop()
{
if (empty())
return std::nullopt;
std::optional<T> value(std::move(slots_[mask(tail_)]));
tail_ = next(tail_);
--count_;
return value;
}
static constexpr std::size_t mask(std::size_t index) noexcept
{
return index & (Capacity - 1);
}
static constexpr std::size_t next(std::size_t index) noexcept
{
return (index + 1) & (Capacity - 1);
}
The SPSC pop and the private write helper behind both push overloads carry the orderings described above. The memory_order reference defines each one.
[[nodiscard]] std::optional<T> pop()
{
const std::size_t tail = tail_.load(std::memory_order_relaxed);
const std::size_t head = head_.load(std::memory_order_acquire);
if (tail == head)
return std::nullopt;
std::optional<T> value(std::move(slots_[mask(tail)]));
tail_.store(tail + 1, std::memory_order_release);
return value;
}
template <typename Value>
bool write(Value&& value)
{
const std::size_t head = head_.load(std::memory_order_relaxed);
// The acquire load pairs with the consumer's release store of tail, so
// the slot at head & mask is free by the time it is written.
const std::size_t tail = tail_.load(std::memory_order_acquire);
if (head - tail >= Capacity)
return false;
slots_[mask(head)] = std::forward<Value>(value);
// Publish the slot write; the consumer's acquire load of head sees it.
head_.store(head + 1, std::memory_order_release);
return true;
}
static constexpr std::size_t mask(std::size_t counter) noexcept
{
return counter & (Capacity - 1);
}
The C++ demo prints the same eight lines as the C program, byte for byte. The tests cover the wrap, the full and empty edges and the optional results. The standard library has no ring buffer type, and Boost.CircularBuffer is the long-standing library option when a general container is wanted. Note that it overwrites the oldest element when full, the opposite of the rings in this article.
Measured: Mask Against Modulo
The indexing experiment runs 100,000,000 push/pop pairs on a 1024-slot ring, once with the mask and once with the modulo, and verifies a checksum over the popped values in both cases. Both functions take the capacity or mask as a runtime argument, so the compiler cannot replace the modulo with a mask on its own.
static unsigned long long run_mask(size_t capacity, size_t mask, double *ns)
{
int *data = malloc(capacity * sizeof *data);
struct timespec start;
struct timespec stop;
unsigned long long checksum = 0;
size_t head = 0;
size_t tail = 0;
size_t pair;
if (data == NULL) {
fputs("bench_wrap: out of memory\n", stderr);
exit(EXIT_FAILURE);
}
if (timespec_get(&start, TIME_UTC) != TIME_UTC)
time_fail();
for (pair = 0; pair < (size_t)PAIRS; ++pair) {
int value = (int)(pair % VALUE_SPAN);
data[head] = value;
head = (head + 1) & mask;
value = data[tail];
tail = (tail + 1) & mask;
sink = value;
checksum += (unsigned long long)(unsigned)value;
}
if (timespec_get(&stop, TIME_UTC) != TIME_UTC)
time_fail();
*ns = elapsed_ns(&start, &stop);
free(data);
return checksum;
}
/* The same workload with index % capacity. capacity is a function argument the
* compiler cannot specialize, so the division really happens. */
static unsigned long long run_modulo(size_t capacity, double *ns)
{
int *data = malloc(capacity * sizeof *data);
struct timespec start;
struct timespec stop;
unsigned long long checksum = 0;
size_t head = 0;
size_t tail = 0;
size_t pair;
if (data == NULL) {
fputs("bench_wrap: out of memory\n", stderr);
exit(EXIT_FAILURE);
}
if (timespec_get(&start, TIME_UTC) != TIME_UTC)
time_fail();
for (pair = 0; pair < (size_t)PAIRS; ++pair) {
int value = (int)(pair % VALUE_SPAN);
data[head] = value;
head = (head + 1) % capacity;
value = data[tail];
tail = (tail + 1) % capacity;
sink = value;
checksum += (unsigned long long)(unsigned)value;
}
if (timespec_get(&stop, TIME_UTC) != TIME_UTC)
time_fail();
*ns = elapsed_ns(&start, &stop);
free(data);
return checksum;
}
Output:
100,000,000 push/pop pairs, capacity 1024
indexing time_ms ns_per_pair
mask 97.1 0.97
modulo 822.5 8.23
The mask version took 97.1 ms and the modulo version 822.5 ms, which is 0.97 ns against 8.23 ns per pair, a factor of about 8.5. The loop does nothing but push and pop on a cached ring, so the two divisions per pair dominate the modulo version, while the mask version measures the loop overhead itself. In a program that does real work per item, most of that gap disappears into the rest of the code. A rerun on a second Linux x86-64 machine gave a factor of about 5, so treat the ratio as machine-specific. The power-of-two capacity costs at most some rounding up of the requested size.
Measured: Lock-Free Against Mutex
The synchronization experiment passes 20,000,000 items from one producer thread to one consumer thread, once through the lock-free SPSC ring and once through a ring protected by a pthread mutex. Both variants check the arrival order and the same checksum, so the comparison covers identical work.
static void *producer_main(void *argument)
{
Work *work = argument;
size_t index;
for (index = 0; index < work->items; ++index) {
int value = (int)(index + 1);
if (work->kind == LOCK_FREE) {
while (!spsc_push(&work->spsc, value)) {
/* Spin: the consumer has not made room yet. */
}
} else {
while (!mutex_ring_push(&work->mutex, value)) {
/* Spin: the consumer has not made room yet. */
}
}
}
return NULL;
}
/* Pops exactly items values, checks they arrive in order and sums them. */
static void *consumer_main(void *argument)
{
Work *work = argument;
size_t received = 0;
size_t expected = 0;
bool order_ok = true;
unsigned long long checksum = 0;
while (received < work->items) {
int value = 0;
bool got;
if (work->kind == LOCK_FREE)
got = spsc_pop(&work->spsc, &value);
else
got = mutex_ring_pop(&work->mutex, &value);
if (got) {
expected++;
if (value != (int)expected)
order_ok = false;
checksum += (unsigned long long)(unsigned)value;
received++;
}
}
work->checksum = checksum;
work->order_ok = order_ok;
return NULL;
}
/* Runs one full produce/consume handoff and times it. */
static bool run_kind(Work *work, RingKind kind, double *time_ms,
double *million_per_second)
{
struct timespec start;
struct timespec stop;
pthread_t producer;
pthread_t consumer;
double elapsed;
work->kind = kind;
work->checksum = 0;
work->order_ok = false;
if (clock_gettime(CLOCK_MONOTONIC, &start) != 0)
return false;
if (pthread_create(&consumer, NULL, consumer_main, work) != 0)
return false;
if (pthread_create(&producer, NULL, producer_main, work) != 0)
return false;
if (pthread_join(producer, NULL) != 0)
return false;
if (pthread_join(consumer, NULL) != 0)
return false;
if (clock_gettime(CLOCK_MONOTONIC, &stop) != 0)
return false;
elapsed = (double)(stop.tv_sec - start.tv_sec) * 1000.0 +
(double)(stop.tv_nsec - start.tv_nsec) / 1000000.0;
*time_ms = elapsed;
*million_per_second = (double)work->items / (elapsed * 1000.0);
return true;
}
Output:
20,000,000 items, one producer and one consumer
implementation time_ms million_items_per_second
lock-free 230.5 86.77
mutex 2144.1 9.33
The lock-free ring took 230.5 ms and the mutex ring 2144.1 ms, 86.77 against 9.33 million items per second, a factor of about 9.3. Each mutex lock and unlock is an atomic read-modify-write on a line that both threads fight over, with the possibility of a kernel wait. The lock-free ring needs one acquire load of the other side’s counter and one release store of its own. The result holds for one producer and one consumer on this machine. The design does not extend to several producers, and a spinning thread wastes CPU when the other side is preempted.
Five Ways a Ring Buffer Passes a Quick Test and Still Fails
Each program below compiles with the house warning flags and prints something plausible, until the output line that gives it away or until a sanitizer stops it. All five are in the C repository’s pitfalls/ directory, and the workflow reruns each one and checks the line or sanitizer summary it should produce.
1. Full and Empty Look the Same
static void ring_push(BrokenRing *ring, int value)
{
ring->data[ring->head] = value;
ring->head = (ring->head + 1) & (CAPACITY - 1);
}
static bool ring_pop(BrokenRing *ring, int *value)
{
if (ring_empty(ring))
return false;
*value = ring->data[ring->tail];
ring->tail = (ring->tail + 1) & (CAPACITY - 1);
return true;
}
int main(void)
{
BrokenRing ring = {{0}, 0, 0};
int value = 0;
size_t index;
setvbuf(stdout, NULL, _IONBF, 0);
puts("full_equals_empty: no count, so head == tail means full and empty");
for (index = 0; index < (size_t)CAPACITY; ++index)
ring_push(&ring, (int)(10 * (index + 1)));
printf("capacity %d, after %d pushes: empty %s, pop -> %s\n", CAPACITY,
CAPACITY, ring_empty(&ring) ? "true" : "false",
ring_pop(&ring, &value) ? "true" : "false");
ring_push(&ring, 50);
fputs("push 50 overwrites 10, the oldest value:", stdout);
for (index = 0; index < (size_t)CAPACITY; ++index)
printf(" %d", ring.data[index]);
putchar('\n');
return 0;
}
Output:
full_equals_empty: no count, so head == tail means full and empty
capacity 4, after 4 pushes: empty true, pop -> false
push 50 overwrites 10, the oldest value: 50 20 30 40
With only head and tail, four pushes fill the ring and head wraps around to equal tail. The empty test then returns true, the pop fails, and the next push overwrites the oldest value. The slots now read 50 20 30 40 while the code still believes the ring is empty. The fix is the count, one word and one increment or decrement per operation.
2. A Mask on a Capacity That Is Not a Power of Two
static void ring_push(BrokenRing *ring, int value)
{
ring->data[ring->head & (CAPACITY - 1)] = value;
ring->head++;
ring->size++;
}
static bool ring_pop(BrokenRing *ring, int *value)
{
if (ring->size == 0)
return false;
*value = ring->data[ring->tail & (CAPACITY - 1)];
ring->tail++;
ring->size--;
return true;
}
int main(void)
{
const int pushed[VALUES] = {10, 20, 30, 40, 50, 60};
BrokenRing ring = {{0}, 0, 0, 0};
int value = 0;
size_t index;
setvbuf(stdout, NULL, _IONBF, 0);
puts("mask_non_power_two: capacity 6 indexed with & 5 collides slots");
for (index = 0; index < (size_t)VALUES; ++index)
ring_push(&ring, pushed[index]);
printf("push 10 20 30 40 50 60 -> size %zu, full %s\n", ring.size,
ring.size == (size_t)CAPACITY ? "true" : "false");
fputs("pop all ->", stdout);
while (ring_pop(&ring, &value))
printf(" %d", value);
putchar('\n');
fputs("expected ->", stdout);
for (index = 0; index < (size_t)VALUES; ++index)
printf(" %d", pushed[index]);
putchar('\n');
return 0;
}
Output:
mask_non_power_two: capacity 6 indexed with & 5 collides slots
push 10 20 30 40 50 60 -> size 6, full true
pop all -> 30 40 30 40 50 60
expected -> 10 20 30 40 50 60
A capacity of 6 masked with & 5 does not wrap like a ring. Five is binary 101, so the mask clears bit 1: indexes 2 and 3 land on slots 0 and 1, and slots 2 and 3 are never used. The pushes of 30 and 40 overwrite 10 and 20, and the pops return 30 40 30 40 50 60 instead of 10 20 30 40 50 60. A mask is only valid for a power-of-two capacity. A ring that must accept any capacity has to use the modulo, or round the capacity up at initialization.
3. An Index That Never Wraps
int main(void)
{
size_t capacity = 4;
BrokenRing ring;
size_t index;
setvbuf(stdout, NULL, _IONBF, 0);
puts("no_wrap: the index advances without masking, so the write leaves the array");
ring.data = malloc(capacity * sizeof *ring.data);
ring.head = 0;
if (ring.data == NULL) {
fputs("no_wrap: out of memory\n", stderr);
return EXIT_FAILURE;
}
for (index = 0; index < capacity; ++index) {
ring.data[ring.head] = (int)(10 * (index + 1));
ring.head++;
}
printf("capacity %zu, after %zu pushes: head %zu, the buffer is full\n",
capacity, capacity, ring.head);
puts("push 50 writes data[4] one slot past the end of the 4-slot buffer");
ring.data[ring.head] = 50; /* AddressSanitizer reports the write here. */
printf("push 50 reported success, head %zu\n", ring.head + 1);
free(ring.data);
return EXIT_SUCCESS;
}
Output:
no_wrap: the index advances without masking, so the write leaves the array
capacity 4, after 4 pushes: head 4, the buffer is full
push 50 writes data[4] one slot past the end of the 4-slot buffer
AddressSanitizer stops the program at the fifth write. Its report, summarized:
ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of size 4, 0 bytes after the 16-byte region allocated in main
SUMMARY: AddressSanitizer: heap-buffer-overflow pitfalls/no_wrap.c:42 in main
The broken ring advances head without masking it. After four pushes head is 4, and the next push writes data[4], one slot past the 16-byte allocation. The fix is one expression: mask every index when it addresses the array, or wrap the index after every increment.
4. Capacity Zero and the Underflowing Mask
int main(void)
{
size_t capacity = 0;
size_t mask;
size_t head = 0;
int *data;
setvbuf(stdout, NULL, _IONBF, 0);
puts("zero_capacity: capacity 0 makes capacity - 1 a huge mask");
mask = capacity - 1;
data = malloc(capacity * sizeof *data);
if (data == NULL) {
fputs("zero_capacity: malloc(0) returned NULL\n", stderr);
return EXIT_FAILURE;
}
printf("capacity %zu, mask %zu\n", capacity, mask);
puts("push 10 writes data[0 & mask], data[0], outside the zero-slot buffer");
data[head & mask] = 10; /* AddressSanitizer reports the write here. */
printf("push 10 reported success, size 1 of capacity %zu\n", capacity);
free(data);
return EXIT_SUCCESS;
}
Output:
zero_capacity: capacity 0 makes capacity - 1 a huge mask
capacity 0, mask 18446744073709551615
push 10 writes data[0 & mask], data[0], outside the zero-slot buffer
AddressSanitizer stops the program at the first write. Its report, summarized:
ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of size 4, 0 bytes after the 1-byte region allocated in main
SUMMARY: AddressSanitizer: heap-buffer-overflow pitfalls/zero_capacity.c:32 in main
This version never validates the capacity, and the common shortcut (capacity & (capacity - 1)) == 0 would not help, because it also accepts zero. The mask becomes SIZE_MAX, 18446744073709551615 on a 64-bit system, and the first push writes data[0] into a zero-byte allocation, which AddressSanitizer tracks as a one-byte region. The fix belongs in initialization: reject zero explicitly, as ring_init and spsc_init do, and reject anything that is not a power of two when a mask will be used.
5. SPSC Without Atomics
static bool ring_push(NonAtomicRing *target, int value)
{
if (target->head - target->tail >= target->capacity)
return false;
target->data[target->head & target->mask] = value;
target->head++;
return true;
}
static bool ring_pop(NonAtomicRing *target, int *value)
{
if (target->tail == target->head)
return false;
*value = target->data[target->tail & target->mask];
target->tail++;
return true;
}
int main(void)
{
pthread_t producer;
pthread_t consumer;
bool created = true;
setvbuf(stdout, NULL, _IONBF, 0);
puts("spsc_nonatomic: the SPSC ring uses plain size_t counters, not atomics");
ring.data = malloc((size_t)CAPACITY * sizeof *ring.data);
if (ring.data == NULL) {
fputs("spsc_nonatomic: out of memory\n", stderr);
return EXIT_FAILURE;
}
ring.capacity = CAPACITY;
ring.mask = CAPACITY - 1;
ring.head = 0;
ring.tail = 0;
if (pthread_create(&consumer, NULL, consumer_main, NULL) != 0)
created = false;
if (created && pthread_create(&producer, NULL, producer_main, NULL) != 0)
created = false;
if (!created) {
fputs("spsc_nonatomic: could not start the threads\n", stderr);
free(ring.data);
return EXIT_FAILURE;
}
(void)pthread_join(producer, NULL);
(void)pthread_join(consumer, NULL);
puts("the handoff finished; the race is what ThreadSanitizer reports, not "
"the count");
free(ring.data);
return EXIT_SUCCESS;
}
Output:
spsc_nonatomic: the SPSC ring uses plain size_t counters, not atomics
consumer received 1000000 items, checksum 500000500000
the handoff finished; the race is what ThreadSanitizer reports, not the count
ThreadSanitizer reports three data races, summarized:
WARNING: ThreadSanitizer: data race
write of head in ring_push (line 39), previous read in ring_pop (line 45)
SUMMARY: ThreadSanitizer: data race pitfalls/spsc_nonatomic.c:39 in ring_push
WARNING: ThreadSanitizer: data race
read of the slot in ring_pop (line 47), previous write in ring_push (line 38)
SUMMARY: ThreadSanitizer: data race pitfalls/spsc_nonatomic.c:47 in ring_pop
WARNING: ThreadSanitizer: data race
write of tail in ring_pop (line 48), previous read in ring_push (line 36)
SUMMARY: ThreadSanitizer: data race pitfalls/spsc_nonatomic.c:48 in ring_pop
The broken ring uses plain size_t counters. ThreadSanitizer reports the producer’s head write against the consumer’s head read, the slot write against the slot read, and the consumer’s tail write against the producer’s tail read. The checksum still came out right in this run, which is why a passing functional test is no evidence that a concurrent ring is correct. Atomic counters with release and acquire are the fix, and the clean ThreadSanitizer run of the real ring is the evidence.
Key Takeaways
- A circular buffer is a fixed array with wrapping write and read indexes. It never allocates after initialization and keeps hard memory bounds in the hot path.
- A power-of-two capacity turns the wrap into
index & (capacity - 1), which cost 0.97 ns per push/pop pair here against 8.23 ns for%. head == tailmeans both empty and full. Keep a count, leave a slot unused or compare free-running counters, or the first full push silently overwrites the oldest value.- One producer and one consumer can share a ring without a mutex. Each side owns one atomic counter, publishes it with a release store and reads the other side’s counter with an acquire load.
- The lock-free SPSC ring moved 86.77 million items per second against 9.33 million for the mutex ring in this run.
- Put the producer and consumer counters on separate cache lines so the cores do not trade one line back and forth.
- ThreadSanitizer is the tool that checks the SPSC claim: the non-atomic pitfall reports three races, and the real ring runs clean.
Frequently Asked Questions
Conclusion
The circular buffer is a small structure built on three ideas. The wrap turns a fixed array into an endless FIFO, and a power-of-two capacity makes the wrap a mask that measured 0.97 ns per push/pop pair against 8.23 ns for the modulo. The full/empty ambiguity waits in every hand-written ring, and a count or free-running counters remove it. The single-producer single-consumer ring shows the payoff of clear ownership: one atomic counter per side, release and acquire, separate cache lines and 86.77 million items per second against 9.33 million for a mutex, with ThreadSanitizer confirming the clean version and catching the broken one.
The data structures hub places the ring beside the queue and the growable array. Use the standard library’s queue or deque when a general FIFO is enough, and write the ring yourself when the memory bound, the wrap and the single-writer hand-off are the requirement.
Source Code and Tests
The programs on this page are in the data-structures/circular-buffer directory of two MYCPLUS example repositories:
| Language | Repository directory | Build status |
|---|---|---|
| C | mycplus/c-examples: data-structures/circular-buffer | |
| C++ | mycplus/cpp-examples: data-structures/circular-buffer |
The examples build and test with CMake:
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure
The demo’s output is compared byte for byte with tests/expected/ordered.txt. The ring tests compare every operation against a reference model over random pushes and pops, and cover the wrap, the full and empty edges and capacity validation. The SPSC tests run a producer and a consumer over a million items and verify the sum. The workflows also run the tests, the demo and the pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer, and the SPSC tests under ThreadSanitizer, where the non-atomic pitfall must report its race. The builds do not check the timings, which belong to one machine.
What I Verified
The example directories contain the test programs and the captured runs. The table states which system ran each check.
| Check | Ubuntu 24.04 (WSL2) | Windows 11 (MSVC) |
|---|---|---|
| Build and tests, C, GCC 13.3, C11 and C17 | Pass (5 of 5 tests) | Not applicable |
| Build and tests, C, Clang 18.1.3, C11 and C17 | Pass (5 of 5 tests) | Not applicable |
Build and tests, C, MSVC 19.44 /W4 /WX | Not applicable | Pass (4 of 4 tests, the pthread and TSan targets are Linux only) |
| Build and tests, C++, g++ 13.3, C++17 and C++20 | Pass (3 of 3 tests) | Not applicable |
| Build and tests, C++, clang++ 18.1.3, C++17 and C++20 | Pass (3 of 3 tests) | Not applicable |
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive- | Not applicable | Pass (3 of 3 tests) |
| AddressSanitizer and UndefinedBehaviorSanitizer, tests, demo and pitfalls | Pass (C 5 of 5, C++ 3 of 3) | Not applicable |
| ThreadSanitizer, SPSC tests | Pass (clean in both languages, and the non-atomic pitfall reports its races) | Not applicable |
| Five pitfalls, each caught by the check named in its section | Pass (2 AddressSanitizer, 1 ThreadSanitizer, 2 output checks) | Not applicable |
| Indexing and synchronization experiments | Run, output in the sections above | Not run |
| Independent rerun on a second Linux x86-64 machine (GCC 13.3 and Clang 18.1.3) | Pass (C 5 of 5, TSan 7 of 7, ASan 5 of 5, C++ 3 of 3), mask about 5 times faster, lock-free faster than mutex | Not applicable |
Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, macOS, weakly ordered CPUs such as ARM, blocking variants, and timings on other machines beyond the rerun above.




