Bird
Raised Fist0
Embedded Cprogramming~7 mins

Ring buffer implementation in Embedded C

Choose your learning style10 modes available
Introduction

A ring buffer helps store data in a fixed-size space that wraps around when full. It is useful to keep data flowing smoothly without losing old data.

When reading data from a sensor continuously and processing it later.
When sending or receiving data over a communication line like UART.
When you want to store recent events or messages in a limited memory area.
When you need a simple queue that reuses memory efficiently.
Syntax
Embedded C
typedef struct {
    int buffer[SIZE];
    int head;
    int tail;
    int max_size;
    bool full;
} RingBuffer;

void ring_buffer_init(RingBuffer *rb, int size);
bool ring_buffer_put(RingBuffer *rb, int data);
bool ring_buffer_get(RingBuffer *rb, int *data);

The head points to where new data is added.

The tail points to where data is read from.

Examples
Create a ring buffer of size 5 and initialize it.
Embedded C
RingBuffer rb;
ring_buffer_init(&rb, 5);
Add two numbers to the ring buffer.
Embedded C
ring_buffer_put(&rb, 10);
ring_buffer_put(&rb, 20);
Read a number from the ring buffer if available.
Embedded C
int value;
if (ring_buffer_get(&rb, &value)) {
    // use value
}
Sample Program

This program creates a ring buffer of size 5. It adds numbers 1 to 5, tries to add a 6th number but fails because the buffer is full. Then it reads all numbers and tries to read once more but finds the buffer empty.

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

#define SIZE 5

typedef struct {
    int buffer[SIZE];
    int head;
    int tail;
    int max_size;
    bool full;
} RingBuffer;

void ring_buffer_init(RingBuffer *rb, int size) {
    rb->head = 0;
    rb->tail = 0;
    rb->max_size = size;
    rb->full = false;
}

bool ring_buffer_put(RingBuffer *rb, int data) {
    if (rb->full) {
        return false; // buffer full
    }
    rb->buffer[rb->head] = data;
    rb->head = (rb->head + 1) % rb->max_size;
    if (rb->head == rb->tail) {
        rb->full = true;
    }
    return true;
}

bool ring_buffer_get(RingBuffer *rb, int *data) {
    if (rb->head == rb->tail && !rb->full) {
        return false; // buffer empty
    }
    *data = rb->buffer[rb->tail];
    rb->tail = (rb->tail + 1) % rb->max_size;
    rb->full = false;
    return true;
}

int main() {
    RingBuffer rb;
    ring_buffer_init(&rb, SIZE);

    // Add numbers 1 to 5
    for (int i = 1; i <= 5; i++) {
        if (ring_buffer_put(&rb, i)) {
            printf("Added %d\n", i);
        } else {
            printf("Buffer full, cannot add %d\n", i);
        }
    }

    // Try to add one more
    if (!ring_buffer_put(&rb, 6)) {
        printf("Buffer full, cannot add 6\n");
    }

    // Read all values
    int val;
    while (ring_buffer_get(&rb, &val)) {
        printf("Read %d\n", val);
    }

    // Try to read from empty buffer
    if (!ring_buffer_get(&rb, &val)) {
        printf("Buffer empty, no data to read\n");
    }

    return 0;
}
OutputSuccess
Important Notes

Remember that the buffer is full when head catches tail after adding data.

When reading, if head equals tail and buffer is not full, it means empty.

Ring buffers are great for fixed memory and continuous data streams.

Summary

A ring buffer stores data in a fixed-size circle.

It uses head and tail pointers to track where to add and read data.

It helps manage data efficiently without moving memory.

Practice

(1/5)
1.

What is the main purpose of the head pointer in a ring buffer?

easy
A. To reset the buffer to empty
B. To indicate where data will be read next
C. To store the total size of the buffer
D. To indicate where new data will be written next

Solution

  1. Step 1: Understand the role of head in ring buffer

    The head pointer marks the position where the next data element will be stored (written) in the buffer.
  2. Step 2: Differentiate head from tail

    The tail pointer is used for reading data, while the head is for writing new data.
  3. Final Answer:

    To indicate where new data will be written next -> Option D
  4. Quick Check:

    Head = write position [OK]
Hint: Head points to write location, tail points to read location [OK]
Common Mistakes:
  • Confusing head with tail pointer
  • Thinking head stores buffer size
  • Assuming head resets the buffer
2.

Which of the following is the correct way to advance the head pointer in a ring buffer of size BUFFER_SIZE after writing one element?

head = ?;
easy
A. head = BUFFER_SIZE - head;
B. head = head + 1;
C. head = (head + 1) % BUFFER_SIZE;
D. head = (head - 1) % BUFFER_SIZE;

Solution

  1. Step 1: Understand circular increment

    To move head forward in a circular buffer, increment and wrap around using modulo with buffer size.
  2. Step 2: Apply modulo operation

    The expression (head + 1) % BUFFER_SIZE ensures head wraps to 0 after reaching the end.
  3. Final Answer:

    head = (head + 1) % BUFFER_SIZE; -> Option C
  4. Quick Check:

    Use modulo to wrap index [OK]
Hint: Use modulo (%) to wrap pointer in ring buffer [OK]
Common Mistakes:
  • Not using modulo causes overflow
  • Subtracting instead of adding
  • Incorrect wrap calculation
3.

Given this code snippet for a ring buffer of size 4, what will be the value of head and tail after these operations?

int head = 0, tail = 0;
int BUFFER_SIZE = 4;

// Write 3 elements
for (int i = 0; i < 3; i++) {
    head = (head + 1) % BUFFER_SIZE;
}

// Read 1 element
tail = (tail + 1) % BUFFER_SIZE;
medium
A. head = 3, tail = 0
B. head = 3, tail = 1
C. head = 2, tail = 1
D. head = 1, tail = 1

Solution

  1. Step 1: Calculate head after writing 3 elements

    Starting at 0, head increments 3 times with modulo 4: head = (0+1)%4=1, then 2, then 3.
  2. Step 2: Calculate tail after reading 1 element

    Tail starts at 0, increments once: tail = (0+1)%4=1.
  3. Final Answer:

    head = 3, tail = 1 -> Option B
  4. Quick Check:

    Head=3, Tail=1 after ops [OK]
Hint: Increment pointers with modulo for each operation [OK]
Common Mistakes:
  • Forgetting modulo wrap
  • Mixing head and tail values
  • Counting increments incorrectly
4.

Identify the bug in this ring buffer write function and select the correct fix:

void write(int data) {
    if ((head + 1) == tail) {
        // Buffer full
        return;
    }
    buffer[head] = data;
    head = (head + 1) % BUFFER_SIZE;
}
medium
A. Change condition to ((head + 1) % BUFFER_SIZE) == tail
B. Remove the condition; buffer never gets full
C. Increment tail instead of head after write
D. Use head == tail to check full buffer

Solution

  1. Step 1: Analyze buffer full condition

    The buffer is full when the next head position wraps to tail, so modulo is needed to wrap index.
  2. Step 2: Correct condition with modulo

    Using ((head + 1) % BUFFER_SIZE) == tail correctly detects full buffer.
  3. Final Answer:

    Change condition to ((head + 1) % BUFFER_SIZE) == tail -> Option A
  4. Quick Check:

    Modulo needed for circular check [OK]
Hint: Always use modulo when comparing circular indices [OK]
Common Mistakes:
  • Missing modulo causes wrong full detection
  • Confusing head and tail roles
  • Incorrectly incrementing tail on write
5.

You want to implement a ring buffer that stores bytes and can hold exactly 8 bytes. Which of these buffer sizes and pointer update methods correctly avoids ambiguity between full and empty states?

Options:
  1. Buffer size = 8, full when (head + 1) % 8 == tail
  2. Buffer size = 9, full when (head + 1) % 9 == tail
  3. Buffer size = 8, full when head == tail
  4. Buffer size = 9, full when head == tail
hard
A. Use buffer size 9 with full condition (head + 1) % 9 == tail
B. Use buffer size 8 with full condition (head + 1) % 8 == tail
C. Use buffer size 8 with full condition head == tail
D. Use buffer size 9 with full condition head == tail

Solution

  1. Step 1: Understand full vs empty ambiguity

    When head == tail, buffer is empty. To distinguish full, buffer size is often set to capacity + 1.
  2. Step 2: Choose buffer size and condition

    Using buffer size 9 for 8 bytes capacity and full condition (head + 1) % 9 == tail avoids ambiguity.
  3. Final Answer:

    Use buffer size 9 with full condition (head + 1) % 9 == tail -> Option A
  4. Quick Check:

    Extra slot avoids full/empty confusion [OK]
Hint: Use buffer size one more than capacity to avoid confusion [OK]
Common Mistakes:
  • Using buffer size equal to capacity causes ambiguity
  • Checking full with head == tail
  • Not reserving one slot for full detection
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard