Reading history

Circular Buffer (Ring Buffer) in C

6 min read 1 views

Build a circular buffer in C: wrap-around indexes, push and pop, full and empty checks, and an overwriting ring for moving averages.

A keyboard driver stores key presses until a program reads them. A serial port collects incoming bytes. A fitness band keeps the last few minutes of heart-rate readings. All of these use a circular buffer, also called a ring buffer: a fixed-size array whose end wraps around to the start. It gives a first-in, first-out queue with no memory allocation and no shifting of data, which is why it is everywhere in embedded and systems programming.

In this lesson you will learn

  • How a ring buffer wraps around with the % operator
  • Keeping track of the head and the count
  • Push and pop, and detecting full and empty
  • An overwriting ring for “the last N values”
  • A fast wrap with & when the size is a power of two

You should know arrays, structures and stacks and queues.

70[0]80[1]30[2]40[3]50[4]wraps4 → 0head = 2 (oldest item: 30)count = 5 (full)pop order:30, 40, 50, 70, 80next slot = (head + count) % 570 and 80 wrapped to slots 0, 1

A Ring Buffer Queue

#include <stdio.h>
#include <stdbool.h>

#define CAP 5

/* A circular (ring) buffer: a fixed array whose ends wrap around */
typedef struct {
    int data[CAP];
    int head;     /* index of the oldest item */
    int count;    /* how many items are stored */
} Ring;

static bool ring_push(Ring *r, int value) {
    if (r->count == CAP) return false;               /* full */
    int tail = (r->head + r->count) % CAP;            /* next free slot */
    r->data[tail] = value;
    r->count++;
    return true;
}

static bool ring_pop(Ring *r, int *out) {
    if (r->count == 0) return false;                  /* empty */
    *out = r->data[r->head];
    r->head = (r->head + 1) % CAP;
    r->count--;
    return true;
}

static void ring_show(const Ring *r) {
    printf("[");
    for (int i = 0; i < r->count; i++)
        printf("%s%d", i ? " " : "", r->data[(r->head + i) % CAP]);
    printf("]  head=%d count=%d\n", r->head, r->count);
}

int main(void) {
    Ring r = {0};
    for (int v = 10; v <= 60; v += 10) {
        if (ring_push(&r, v)) printf("push %d  ", v);
        else                  printf("push %d refused (full)  ", v);
        ring_show(&r);
    }

    int x = 0;
    for (int i = 0; i < 2; i++) {
        if (ring_pop(&r, &x)) printf("pop -> %d  ", x);
        ring_show(&r);
    }

    ring_push(&r, 70);
    ring_push(&r, 80);
    printf("after pushing 70, 80 (wrapped around): ");
    ring_show(&r);
    printf("raw array: ");
    for (int i = 0; i < CAP; i++) printf("%d ", r.data[i]);
    printf("\n");

    while (ring_pop(&r, &x)) printf("%d ", x);
    printf("<- popped all, FIFO order\n");
    return 0;
}

Output

push 10  [10]  head=0 count=1
push 20  [10 20]  head=0 count=2
push 30  [10 20 30]  head=0 count=3
push 40  [10 20 30 40]  head=0 count=4
push 50  [10 20 30 40 50]  head=0 count=5
push 60 refused (full)  [10 20 30 40 50]  head=0 count=5
pop -> 10  [20 30 40 50]  head=1 count=4
pop -> 20  [30 40 50]  head=2 count=3
after pushing 70, 80 (wrapped around): [30 40 50 70 80]  head=2 count=5
raw array: 70 80 30 40 50 
30 40 50 70 80 <- popped all, FIFO order
  • head is the index of the oldest item, and count is how many items are stored. The next free slot is (head + count) % CAP.
  • The % operator makes indexes wrap: with a capacity of 5, the slot after index 4 is index 0.
  • When count equals the capacity, the buffer is full and ring_push refuses 60. When count is 0, ring_pop reports that it is empty.
  • Popping does not move any data. It just advances head, so every operation takes the same short time, however many items there are.
  • After two pops, 70 and 80 went into slots 0 and 1, at the start of the array. The raw array reads 70 80 30 40 50, but the logical order, starting from head = 2, is still 30 40 50 70 80.
  • Items come out in the order they went in: first in, first out.

An Overwriting Ring: The Last N Values

#include <stdio.h>

#define CAP 4

/* Overwriting ring buffer: keeps only the most recent CAP readings.
   Useful for "last N values", such as a moving average of sensor data. */
typedef struct {
    double data[CAP];
    int next;     /* where the next value goes */
    int count;
    double sum;
} Window;

static void window_add(Window *w, double v) {
    if (w->count == CAP)
        w->sum -= w->data[w->next];    /* drop the oldest value */
    else
        w->count++;
    w->data[w->next] = v;
    w->sum += v;
    w->next = (w->next + 1) % CAP;
}

static double window_avg(const Window *w) {
    return w->count ? w->sum / w->count : 0.0;
}

int main(void) {
    Window w = {0};
    double temps[] = {29.0, 31.0, 30.0, 33.0, 35.0, 34.0, 28.0};
    printf("reading  avg of last %d\n", CAP);
    for (int i = 0; i < 7; i++) {
        window_add(&w, temps[i]);
        printf("%7.1f  %8.2f\n", temps[i], window_avg(&w));
    }

    /* Power-of-two capacity: & (CAP - 1) works like % CAP but is cheaper */
    for (int i = 5; i <= 9; i++)
        printf("%d %% %d = %d,  %d & %d = %d\n", i, CAP, i % CAP, i, CAP - 1, i & (CAP - 1));
    return 0;
}

Output

reading  avg of last 4
   29.0     29.00
   31.0     30.00
   30.0     30.00
   33.0     30.75
   35.0     32.25
   34.0     33.00
   28.0     32.50
5 % 4 = 1,  5 & 3 = 1
6 % 4 = 2,  6 & 3 = 2
7 % 4 = 3,  7 & 3 = 3
8 % 4 = 0,  8 & 3 = 0
9 % 4 = 1,  9 & 3 = 1
  • This version never refuses a value. When it is full, the newest reading overwrites the oldest, so it always holds the latest 4 readings.
  • It keeps a running sum: subtract the value being overwritten, then add the new one. The average is always one division away, with no loop.
  • This is a moving average, used to smooth noisy sensor readings, prices or network speeds.
  • When the capacity is a power of two, i & (CAP - 1) gives the same result as i % CAP for non-negative i, using a cheap bit operation. The table at the end shows they match.
OperationRing bufferArray that shifts items
Add at the backO(1)O(1)
Remove from the frontO(1)O(n), every item moves
MemoryFixed, set in advanceFixed or growing

Common Mistakes

  1. Tracking only head and tail. When head equals tail, you cannot tell if the buffer is full or empty. Keep a count, or leave one slot always empty.
  2. Forgetting to wrap one of the indexes, which writes past the end of the array.
  3. Using & (CAP - 1) when the capacity is not a power of two. It then gives wrong indexes.
  4. Sharing a ring between an interrupt or thread and the main code without care. Use one writer and one reader, with atomic or volatile indexes as the platform requires.

Practice Exercises

Exercise 1. A ring of capacity 8 has head = 6 and count = 5. Which array slots hold the items, in order?

Show answer

6, 7, 0, 1, 2. Each index is (6 + i) % 8 for i = 0 to 4.

Exercise 2. Add a function bool ring_peek(const Ring *r, int *out) that reads the oldest item without removing it.

Show answer
static bool ring_peek(const Ring *r, int *out) {
    if (r->count == 0) return false;
    *out = r->data[r->head];
    return true;
}

Frequently Asked Questions

What happens when a ring buffer is full?

That is a design choice. A queue of commands should refuse new items (or make the writer wait), so nothing is lost. A log of recent readings should overwrite the oldest, because only the latest values matter.

Can a ring buffer grow?

It can, by allocating a bigger array and copying the items across in logical order, starting from head. Most uses keep a fixed size, though, because predictable memory is one of the main reasons to choose a ring buffer.

Summary

  • A ring buffer is a fixed array whose indexes wrap around with % CAP.
  • Track head and count; push at (head + count) % CAP, pop at head.
  • Every operation is O(1), with no data moved and no memory allocated.
  • An overwriting ring keeps the last N values, ideal for moving averages.

Next: Binary Heap and Priority Queue in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *