A ring buffer (circular buffer) is a classic data structure question in embedded interviews when discussing how to implement a UART receive buffer. Based on the official Linux kernel documentation on circular buffers and a C program verified with gcc (Debian 14.2.0-19) 14.2.0, this post explains how head and tail move, how to distinguish full from empty, and what to watch out for when using a ring buffer with an interrupt service routine (ISR).

Summary

A ring buffer is a queue that treats a fixed-size array as if its end wraps back to its start. Only the write index (head) and read index (tail) move, wrapping around to 0 when they pass the end. When head == tail, the buffer is empty; in the scheme that leaves one slot empty, the buffer is full when the slot right after head is tail, so a buffer of size 8 stores up to 7 items. With a single producer (UART receive ISR) and a single consumer (main loop), it can operate without a lock when index accesses are properly ordered.

What is a ring buffer?

One-line answer: A ring buffer is a queue structure built on a fixed-size array whose end wraps around to its start, advancing only the write (head) and read (tail) indices without shifting existing data forward.

In a naive array queue, removing an item from the front requires shifting all remaining elements forward by one slot. By contrast, a ring buffer (circular buffer) keeps elements in place and moves only two indices:

  • head: The index where the producer inserts new items.
  • tail: The index where the consumer takes items out.

As a concise interview answer, you can define it as “a fixed-size FIFO queue that wraps back to index 0 at the end of the array and updates only the head and tail indices without moving stored elements.”

How do head and tail move?

One-line answer: Writing advances head and reading advances tail by one slot, wrapping from the end back to index 0 using a bitwise AND (& (SIZE - 1)) instead of modulo when the buffer size is a power of two.

According to the Linux kernel documentation on circular buffers, choosing a power-of-two buffer size allows wrapping indices with a bitwise AND operation (& (SIZE - 1)) rather than a modulo operation.

The following ringbuf.c program has no concurrency handling and is solely for checking the concept (Korean comments inside the code state: size 8 power of two, leave-one-slot-empty scheme, single-producer/single-consumer assumption, no concurrency handling, head for write position and tail for read position, wrapping past the end back to slot 0). It was compiled without warnings on x86_64 using gcc (Debian 14.2.0-19) 14.2.0 with gcc -std=c11 -Wall -Wextra ringbuf.c -o ringbuf.

ringbuf.c:

/* 링 버퍼: 크기 8(2의 거듭제곱), "한 칸 비워 두기" 방식. 단일 생산자/단일 소비자 가정, 동시성 처리 없음(개념 확인용) */
#include <stdio.h>
#include <stdint.h>
#define SIZE 8u
#define MASK (SIZE - 1u)
static uint8_t buf[SIZE];
static unsigned head = 0, tail = 0;            /* head: 쓰기 위치, tail: 읽기 위치 */
static int is_empty(void) { return head == tail; }
static int is_full(void)  { return ((head + 1u) & MASK) == tail; }
static int put(uint8_t c) { if (is_full()) return 0; buf[head] = c; head = (head + 1u) & MASK; return 1; }
static int get(uint8_t *c) { if (is_empty()) return 0; *c = buf[tail]; tail = (tail + 1u) & MASK; return 1; }
int main(void) {
    int n = 0;
    for (uint8_t c = 'A'; c <= 'J'; c++) { if (put(c)) n++; else { printf("put('%c') failed: full\n", c); break; } }
    printf("stored=%d (SIZE=%u, one slot always empty)\n", n, SIZE);
    uint8_t c; printf("read 3: ");
    for (int i = 0; i < 3 && get(&c); i++) printf("%c", c);
    printf("\n");
    put('X'); put('Y'); put('Z');                 /* 끝을 지나 0번 칸으로 돌아감 */
    printf("head=%u tail=%u (head wrapped)\n", head, tail);
    printf("read all: ");
    while (get(&c)) printf("%c", c);
    printf("\nempty=%d\n", is_empty());
    return 0;
}

Program output:

put('H') failed: full
stored=7 (SIZE=8, one slot always empty)
read 3: ABC
head=2 tail=3 (head wrapped)
read all: DEFGXYZ
empty=1

Tracing the code and output step by step:

  1. Characters 'A' through 'G' fill 7 slots, and 'H' is refused because the next slot after head is tail (stored=7).
  2. Reading 3 items produces ABC and moves tail to 3.
  3. Putting 'X', 'Y', and 'Z' moves head past the end of the array back to slots 0, 1, and 2, so head=2 is now less than tail=3 (head wrapped).
  4. Reading all remaining items produces DEFGXYZ in order, leaving the buffer empty again (empty=1).

Ring buffer of size 8: head and tail advance around the array and wrap from the end back to index 0

How do you distinguish full from empty?

One-line answer: You either reserve head == tail for empty and leave one slot unused so ((head + 1) & MASK) == tail indicates full, or maintain a separate count variable.

If every slot in the array were filled, head would catch up to tail and make head == tail true for both empty and full states. Two common schemes resolve this ambiguity:

  • Leave one slot empty: Used in the Linux kernel circular buffer documentation and the example above. Here, head == tail means empty, and the buffer is full when head is one slot behind tail (that is, the next slot after head is tail). Because one slot is always left empty, a buffer of size 8 holds at most 7 items.
  • Keep a separate count variable: Tracks the number of stored items explicitly so all slots can be used. However, because both the producer and the consumer update count, it requires extra care when used with an ISR.
AspectLeave One Slot EmptySeparate count Variable
Empty conditionhead == tailcount == 0
Full condition((head + 1) & MASK) == tail (next slot is tail)count == SIZE
Usable slotsOne slot is always left empty (SIZE - 1 usable)All slots are usable (SIZE usable)
ISR concurrencyProducer writes only head; consumer writes only tailBoth sides modify count, requiring extra care

Empty when head equals tail; full when the slot after head is tail (leave-one-slot scheme) compared with a count variable

What should you watch out for when using it with a UART interrupt?

One-line answer: Under the single-producer (ISR) and single-consumer (main loop) condition, ensure the ISR writes only head and the main loop writes only tail, store the data before updating the index, and decide on a policy when the buffer is full.

For choosing between interrupt-driven reception and polling in embedded interviews, see How to choose between interrupts and polling in an embedded interview (Korean); for comparing UART with other serial buses, see I2C vs SPI vs UART differences in embedded interviews. When designing a ring buffer where a UART receive ISR acts as the producer and the main loop acts as the consumer, keep these principles in mind:

  • State the single-producer / single-consumer condition: As noted in the Linux kernel documentation, a circular buffer can be used without a lock—relying on memory barriers and ordered index access (such as smp_store_release and READ_ONCE-style access in the kernel)—only when there is exactly one producer and one consumer. Never claim it is “always safe without a lock” without stating this condition.
  • Separate index ownership: The ISR (producer) writes only head, and the main loop (consumer) writes only tail.
  • Write data first, update index after: The producer must write the byte into the buffer slot before advancing head so the consumer never sees an updated index pointing to unwritten data.
  • Prevent compiler caching when reading the other side’s index: Read the other side’s index using volatile or atomic access in C (or std::atomic in C++; see How C++ std::atomic prevents data races (Korean)) so the compiler does not cache the value in a register.
  • Decide a policy when full: Choose whether to drop newly arriving data or overwrite the oldest data when the buffer fills up. For a real-world example of hardware receive FIFO overflow when incoming frames are not drained in time, see What to check first when mcp251xfd FIFO overflow drops RX on can0 (Korean).

What follow-up questions come up in interviews?

One-line answer: Interviewers commonly ask how to handle multiple producers, why the buffer size is chosen as a power of two, and how index handling changes when receiving via DMA.

What if there are multiple producers?

When there are multiple producers, their access must be serialized with a lock so they do not overwrite each other’s updates to head. For when to use a spinlock versus a mutex in embedded and kernel contexts, see When to use a spinlock instead of a mutex in embedded and kernel interviews (Korean).

Why make the buffer size a power of two?

If the size is a power of two, wrapping the index around the end of the buffer can be done with a bitwise AND operation (& (SIZE - 1)) instead of a modulo operation.

What is different when using it with DMA?

With DMA, the DMA controller acts as the producer writing directly into memory, and software reads the hardware transfer position to see how far new data has been written. For how DMA compares with CPU copying in embedded interviews, see What is DMA and how does it differ from CPU copy in embedded interviews.

One-line answer: Here are related posts covering interrupts versus polling, UART comparisons, DMA, spinlocks, hardware FIFO overflow, and C++ atomic operations.

What are the sources?

One-line answer: This post is based on the circular buffers guide in the official Linux kernel documentation and our GCC reproduction.