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.
Stay Subscribed
Follow me on twitter @hoboben, subscribe to the RSS feed or get updates by e-mail.
You can also contact me directly - I make an effort to reply to every e-mail.