
Recall first from Linked lists
- A linked list stores one allocation per node; a dummy head node removes the empty-list and head-deletion special cases.
- Two links make doubly-linked deletion O(1), which is the idea behind the kernel's intrusive list_head.
- A pointer-to-pointer delete loop rewires whichever link points at the victim, so head and middle deletion need no branch.
Ring buffer basics
5 min readLinked lists give you dynamic size but scatter nodes across the heap; sometimes a fixed buffer is what you need. This lesson answers how to build a ring buffer and how to make generic code own its data safely.
A a fixed-capacity buffer where write and read positions wrap around the end back to the start, used to pass a stream between a producer and a consumer, also called a circular buffer, is the standard way to buffer a stream when memory is limited, as it almost always is on a board. It is one array, allocated once, plus two indices.
#define CAP 8
struct ring {
int buf[CAP];
int head; /* where the next element is written */
int tail; /* where the next element is read from */
int count; /* how many elements are currently stored */
};
The names are conventional but not universal, so be explicit in your own code. Here head is the write position and tail is the read position. Pushing writes at head and advances it; popping reads from tail and advances it. The key is that both indices wrap with a modulo operation, so after slot CAP - 1 comes slot 0 again.
int ring_push(struct ring *r, int v) {
if (r->count == CAP)
return -1; /* full, do not write */
r->buf[r->head] = v;
r->head = (r->head + 1) % CAP; /* wrap around */
r->count++;
return 0;
}
int ring_pop(struct ring *r, int *out) {
if (r->count == 0)
return -1; /* empty, nothing to read */
*out = r->buf[r->tail];
r->tail = (r->tail + 1) % CAP;
r->count--;
return 0;
}
Check capacity: on push, refuse if
countisCAP; on pop, refuse ifcountis zero.Touch the slot: push stores at
buf[head]; pop reads frombuf[tail].Advance the index: move
headortailforward by one.Wrap with modulo:
(index + 1) % CAPsends the last slot back to slot zero.Update the count: increment on push, decrement on pop, so empty and full stay exact.
The hardest part of a ring buffer is telling empty from full, because both can leave the two indices equal. Two standard solutions exist. The first, used above, is a count field: zero means empty and CAP means full, and the tests are exact. The second is the sentinel slot: you declare the buffer full when the write position would run into the read position, so one slot always stays empty and usable capacity is CAP - 1.
int ring_empty(const struct ring *r) { return r->head == r->tail; }
int ring_full (const struct ring *r) { return (r->head + 1) % CAP == r->tail; }
A buffer with a sentinel slot needs no count field, which saves a variable and an update, at the cost of one unused slot. The choice is a tradeoff between an extra integer and a wasted slot, and either is correct as long as you never mix the two designs.
The other policy decision is what happens when the buffer is full. A blocking (or error-returning) buffer refuses the write, as above, so no data is lost and the producer must retry or wait. An overwriting buffer instead advances the tail too, so the newest value overwrites the oldest, which suits a display of the latest reading where old values are worthless.
A serial driver receives bytes from hardware in an interrupt that cannot wait for slow software, so the interrupt handler pushes each byte into a ring buffer and returns, and the application pops bytes when it is ready. The fixed array means the driver never allocates memory inside an interrupt, where the kernel allows only non-sleeping GFP_ATOMIC allocations that may fail under pressure, and the wrap makes a small buffer absorb bursts larger than its capacity. This is the same structure you will meet again in the networking and driver modules.
learner@embeddex:~/lab$ # count tells empty from full; head and tail wrap with % CAP learner@embeddex:~/lab$ gcc -o ring ring.c learner@embeddex:~/lab$ # head wrapped to 0 after 8 pushes; the drain recovers 13..20, nothing l ost learner@embeddex:~/lab$ ./ring after 8 pushes: head=0 tail=0 count=8 after 3 pops: head=0 tail=3 count=5 after 3 more: head=3 tail=3 count=8 push when full returns -1 drain: 13 14 15 16 17 18 19 20 learner@embeddex:~/lab$ # for a power-of-two CAP the modulo is a single bitwise AND learner@embeddex:~/lab$ gcc -o mask mask.c learner@embeddex:~/lab$ # (h+1)%8 and (h+1)&7 agree, including the 7 -> 0 wrap learner@embeddex:~/lab$ ./mask head 0: +1%8 = 1, +1&7 = 1 head 1: +1%8 = 2, +1&7 = 2 head 2: +1%8 = 3, +1&7 = 3 head 3: +1%8 = 4, +1&7 = 4 head 4: +1%8 = 5, +1&7 = 5 head 5: +1%8 = 6, +1&7 = 6 head 6: +1%8 = 7, +1&7 = 7 head 7: +1%8 = 0, +1&7 = 0 head 8: +1%8 = 1, +1&7 = 1
Ring buffer efficiency and the producer/consumer split
3 min readWhen the capacity is only known at run time, the modulo in (index + 1) % cap compiles to an integer division, one of the slowest instructions on any CPU, and many small ARM cores have no divide instruction at all. If the capacity is a power of two, the same wrap is a single bitwise AND against CAP - 1, because masking keeps only the low bits, and those low bits cycle through exactly CAP values. With a compile-time constant such as #define CAP 8, the compiler already makes this substitution for unsigned indices; writing the mask yourself makes it explicit and works for run-time power-of-two sizes too.
#define CAP 8 /* a power of two */
/* these are equivalent when CAP is a power of two */
r->head = (r->head + 1) % CAP;
r->head = (r->head + 1) & (CAP - 1);
The mask keeps the index in the range 0 to CAP - 1 with no division, which is why real-time and driver code sizes ring buffers to a power of two. The same trick appears everywhere a counter wraps, from hash tables to the kernel's own queues.
Try the mask below: toggle bits above bit 2 and watch the wrapped slot hold its low three bits.
The second efficiency idea is structural rather than arithmetic. In a a buffer with exactly one writer and one reader, so the two indices are each owned by one side and need no locking (SPSC) buffer built with the sentinel-slot design, the producer writes only head and the consumer writes only tail; each side merely reads the other's index to test full or empty. Because no variable has two writers, the two sides do not need a mutex, and this layout is the building block for a lock-free queue.
/* producer: reads tail, writes buf[head] then head */
/* consumer: reads head, reads buf[tail] then writes tail */
The count design does not work here. Both sides would update count, the producer incrementing and the consumer decrementing, and count++ is a read-modify-write that two threads can interleave, losing an update. That is why lock-free SPSC buffers use the sentinel slot, or free-running indices compared by subtraction, instead of a shared counter. This is a preview, not a promise: making a truly lock-free SPSC ring buffer correct across CPU cores requires memory barriers and atomic operations, which are module M2 territory. The design you build now, with its split of head and tail ownership, is the shape that survives when the barriers are added later.
Going deeperWhy one producer and one consumer is a special case
With two producers both writing to head, the sequence "read head, write buf[head], store head+1" races: both threads can read the same head, both write the same slot, and one element is silently lost. This is the classic lost-update race, and volatile does not fix it, because volatile only forces memory access and says nothing about ordering between threads. The SPSC buffer sidesteps the race by construction: only one thread ever writes head, so the read-modify-write of that index is not shared. This is exactly why the embedded convention is to give the interrupt handler one index and the main loop the other, and to add atomics only when a second writer appears.
Genericity, ownership and common mistakes
5 min readSo far the nodes stored an int. To store anything else, change the struct and recompile, or make the node code written against a void* and function pointers so it works on data of any type without modification. The generic node stores a void * pointing at the caller's data.
struct node {
void *data; /* points at a caller-owned object */
struct node *next;
};
A void * can hold the address of anything, so one list implementation serves every element type. The price is that the compiler no longer knows the type, so you cast the void * back before use, and you supply the missing operations as function pointers. This is the pairing from the callbacks section: void * carries the data and a function pointer carries the behaviour.
typedef int (*pred_fn)(const void *item, void *context);
struct node *find_if(struct node *head, pred_fn pred, void *context) {
for (struct node *cur = head; cur != NULL; cur = cur->next)
if (pred(cur->data, context)) /* call back with each item */
return cur;
return NULL;
}
find_if finds any node whose payload satisfies a caller-supplied predicate, without knowing what the payload is. The same shape, a void * plus a function pointer, is how qsort works, and it is the closest C gets to the polymorphism of other languages. A C++ class with virtual functions compiles to a struct whose first member is a pointer to a table of function pointers, the vtable; calling a virtual method is a load from that table and an indirect call. A Rust trait object is a data pointer plus a vtable pointer. All three are the dispatch table from earlier, wearing different syntax.
The other half of genericity is ownership, and this is where most of the bugs live. A node that stores a void * stores only the pointer, not the pointed-to object. Freeing the node frees only the node's own bytes, the two pointers; the object it pointed at is untouched, and if nobody else frees it, it leaks. If both the list and the caller free it, the program double-frees and glibc aborts with a message like "free(): double free detected in tcache 2". The rule that prevents both is a stated contract: exactly one owner frees each object, either the list on removal or the caller after removal, never both and never neither.
/* contract: the list owns payloads and frees them on delete */
int delete_owned(struct node **head, void *key, int (*eq)(const void *, const void *)) {
struct node **cur = head;
while (*cur && !eq((*cur)->data, key))
cur = &(*cur)->next;
if (!*cur)
return 0;
struct node *victim = *cur;
*cur = victim->next;
free(victim->data); /* the list owns the payload, so it frees it */
free(victim);
return 1;
}
C has no built-in generic container, so projects build them from macros. The BSD <sys/queue.h> header defines intrusive, macro-based singly and doubly linked lists, and the kernel's list.h provides LIST_HEAD, list_for_each_entry and friends. Macros generate the type-specific code at compile time, so they stay type-safe where void * does not, at the cost of harder-to-read errors. The void * plus function pointer approach is the portable, readable default; the macro approach is the performance and type-safety ceiling.
The three mistakes to internalise, each diagnosed from its symptom: a use-after-free when deleting while traversing, fixed by saving next before free; a ring buffer that confuses empty and full, fixed by a count field or a sentinel slot; and a double free from unclear ownership, fixed by a written contract of who frees what.
C will not stop you from freeing a payload twice or never freeing it. State the ownership rule in a comment next to the struct, and make every delete path follow it. AddressSanitizer and Valgrind, which you met in the memory lesson and will use more in the next one, turn an ownership mistake from a mystery crash into a pinpointed report.
Going deeperConverting between function and object pointers is not portable
A void * can hold an object pointer, but the C standard does not guarantee it can hold a function pointer, because on some historical machines code and data live in different address spaces with different widths. Assigning a function pointer to a void * and back is therefore not portable C. POSIX systems, including Linux, define dlsym to return a void * that may be a function address, so on those systems the round trip works, but strictly conforming code stores function pointers in function-pointer types only. This is one more reason the callback idiom passes the code as a typed function pointer and the data as a separate void *, rather than trying to smuggle both through one value.
Try it
1 min readOpen your lab environment and build a dispatch-table menu first: define a cmd_fn typedef, an array of handlers, and a loop that reads a command number, validates it against the table size, and calls the entry. Then implement a singly linked list with push_front, push_back (keeping a tail), find, print_all and delete_key, and drive it with a test that deletes from an empty list, a single-node list, the head, the middle and the tail, printing after each step. Finally implement a ring buffer with push and pop, and write a test that fills it to CAP, empties it, and pushes and pops enough values to force the indices to wrap past the end, printing the indices to prove no data is lost. The practice pack turns each of these into graded exercises with the edge cases called out.
Key takeaways
- A ring buffer reuses a fixed array with head and tail indices; a count or a sentinel slot disambiguates empty from full.
- Store void* payloads for genericity but document who owns and frees the pointed-to data.
- A power-of-two capacity replaces modulo with a bitwise AND, which is why real-time and driver code sizes ring buffers to powers of two.
- In a single-producer single-consumer buffer each index has one writer, so the two sides need no mutex.
Reflect
- Explain to a colleague, in two sentences: implement a ring buffer with wraparound and distinguish the empty and full states using a count field or a sentinel slot.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.