This content is provided AS IS for archive purposes only. Content may be out of date with no guarantee of correctness.

Circular Buffer C Implementation - Manuals

Main Article

Circular Buffer C Implementation

A circular buffer or ring buffer is a fixed-size data structure that wraps from end to end. New data overwrites older data, but it can be written to infinitely. This makes it ideal for buffering keyboard input or streaming data, like real-time sound or video, where old data less important.

It looks simple, but it can be unintuitive to implement when you are used to linear memory.

Here is a simple C implementation which I release into the public domain (you are free to use it without credit):

#define BUFFER_SIZE 256

item *buffer[BUFFER_SIZE];
int start = 0;
int end = 0
int active = 0;

void PushToQueue(item *p)
{
    buffer[end] = p;
    end = (end + 1) % BUFFER_SIZE;

    if (active < BUFFER_SIZE)
    {
        active++;
    } else {
        /* Overwriting the oldest. Move start to next-oldest */
        start = (start + 1) % BUFFER_SIZE;
    }
}

item *RetrieveFromQueue(void)
{
    item *p;

    if (!active) { return NULL; }

    p = buffer[start];
    start = (start + 1) % BUFFER_SIZE;

    active--;
    return p;
}

Notice how the modulus operator is used to wrap the pointers into the buffer range.

Affiliate Link: Tawesoft may recieve a commission for recommending this book.

For more info, look up Queues in Chapter 10.1 of the CLRS Algorithms book; page 234 in the Third Edition. It has diagrams and pseudocode and is a great resource for learning about data structures.

CLRS: Introduction to Algorithms

The CLRS Algorithms book is a good resource for learning about data structures

Stay Subscribed

This website is in the process of being archived. But don't worry! We won't be breaking any links or bookmarks!

The most popular content will be revised, updated and improved and added to the Tawesoft Knowledge Base.

If a page on this website has been improved, we will automatically redirect any vistors to the updated version.

Otherwise, we'll keep the old content available for many years to come.


Login
v0.34.archive