pointers-memory · advanced · ~15 min

Circular ring buffer split-copy

Manage wrap-around pointer arithmetic and split memory copies in circular ring buffers.

Challenge

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.

Your Task

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.

Rules

  1. Available space in the buffer is cap - *count. You may write at most to_write = min(n, cap - *count).
  2. If to_write == 0 or any pointer is NULL, return 0.
  3. If writing to_write bytes from *head wraps past cap, split the write into:
    • First chunk: from ring + *head up to the end of the buffer (cap - *head bytes).
    • Second chunk: remaining bytes starting from index 0.
  4. Update *head = (*head + to_write) % cap.
  5. Update *count += to_write.
  6. Return to_write (the number of bytes successfully written).

Input format

ring: storage array; cap: capacity; head: write index; count: current occupancy; src: bytes to write; n: requested count.

Output format

Returns size_t count of bytes written.

Constraints

C11 freestanding. Never overwrite unread bytes; split memcpy across boundaries.

Starter code

#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;
}

Common mistakes

Writing more than available space (cap - *count); off-by-one boundary calculation; forgetting to update *count.

Edge cases to handle

Ring full returns 0; write fits before boundary; write splits across boundary; wrap lands exactly at index 0.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.