liveBook · Manning

Circular buffer

As explained in Modern C, Third Edition

A circular buffer is a fixed-capacity queue-like data structure whose logical sequence wraps around the end of an underlying array.

A circular buffer stores a logical sequence in a dynamically allocated array. Elements may be appended or removed from the front while the sequence wraps from the array's end back to its beginning. section 13.1.1

 struct circular {
   size_t  start [[deprecated("privat")]]; /* First element     */
   size_t  len   [[deprecated("privat")]]; /* Number of elements*/
   size_t  cap   [[deprecated("privat")]]; /* Maximum capacity  */
   double* tab   [[deprecated("privat")]]; /* Data array        */
 };

The representation tracks the first logical element with start, the element count with len, capacity with cap, and storage with tab. section 13.1.1

Initialization and use

A typical lifetime begins with `circular circ; circular_init(&circ, 100);` and ends with `circular_destroy(&circ);`. The interface also provides element access, length queries, and resizing. Access translates a logical position by adding start and reducing it modulo cap. Resizing may return a different pointer, so its `[[nodiscard]]` result must be used; shrinking below the current length fails. section 13.1.1

Correct resizing preserves wrapped data by reallocating storage and, when the sequence occupies two physical chunks, copying or moving one chunk into the new layout. Allocation failure leaves the resize unsuccessful. section 13.1.1

How Modern C, Third Edition covers it

How deep it goes
Descends from interface design to modulo indexing, allocation, pointer replacement, and wrapped-data movement during resizing.
Examples
Uses a double-valued circular object initialized with capacity 100 and represented by start, len, cap, and tab fields.
What it assumes
Assumes familiarity with C structures, pointers, dynamic allocation, arrays, and size_t-based indexing.
What you can do after
Operate/configure a circular buffer through initialization, destruction, element access, length queries, and resizing.
How it connects
Connects dynamic arrays, malloc, realloc, memcpy, memmove, pointers, and modulo arithmetic.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.