pointers-memory · advanced · ~15 min
Manage wrap-around pointer arithmetic and split memory copies in circular ring buffers.
Circular ring buffers store streaming bytes in a fixed-size array. Because the write cursor (head) wraps from the end of the buffer back to index 0, writing $N$ bytes often requires splitting the operation into two contiguous memcpy() calls.
Implement:
size_t ring_buffer_write(char *ring, size_t cap, size_t *head, size_t *count, const char *src, size_t n);
Write up to n bytes from src into circular buffer ring.
cap - *count. You may write at most to_write = min(n, cap - *count).to_write == 0 or any pointer is NULL, return 0.to_write bytes from *head wraps past cap, split the write into:ring + *head up to the end of the buffer (cap - *head bytes).0.*head = (*head + to_write) % cap.*count += to_write.to_write (the number of bytes successfully written).ring: storage array; cap: capacity; head: write index; count: current occupancy; src: bytes to write; n: requested count.
Returns size_t count of bytes written.
C11 freestanding. Never overwrite unread bytes; split memcpy across boundaries.
#include <stddef.h>
/* Write up to n bytes from src into circular ring buffer.
Handles wrap-around split writes. Updates *head and *count.
Returns bytes written. */
size_t ring_buffer_write(char *ring, size_t cap, size_t *head, size_t *count, const char *src, size_t n) {
(void)ring; (void)cap; (void)head; (void)count; (void)src; (void)n;
return 0;
}
Writing more than available space (cap - *count); off-by-one boundary calculation; forgetting to update *count.
Ring full returns 0; write fits before boundary; write splits across boundary; wrap lands exactly at index 0.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.