ProblemsMemory ManagementCircular buffer
IntermediateMemory Management

Circular buffer

Context

Firmware for a device with 64KB of RAM and a defense-industry client. Runtime allocation is forbidden by a regulation nobody has read in full but everyone fears. Telemetry must go into a fixed-size ring: oldest entries get overwritten, newest survive. Write the buffer — and remember that around here new equals a formal reprimand.

Task

Implement a fixed-capacity CircularBuffer<T> (ring buffer) with FIFO semantics, write/read, and an overwrite that replaces the oldest element when full.

Adapted from exercism/cpp (MIT).

Constraints

  • Fixed capacity set at construction
  • read() returns oldest element (FIFO); throws if empty
  • write() appends; throws if full
  • overwrite() writes even when full, dropping the oldest element
  • clear() empties the buffer; empty()/full() report state

Before you code

  • Why is a ring buffer preferred over re-shifting a vector?
  • How do the head and tail indices wrap around?
  • What is the difference in behaviour between write and overwrite when full?

Tests

  • #1FIFO read returns oldest first
  • #2Read from empty throws
  • #3Full write throws, overwrite replaces oldest
  • #4clear empties the buffer
  • #5Wraparound: cycling past capacity keeps FIFO order

Hints

Hint 1

Keep head, tail, and size indices into a fixed-capacity array; wrap with % capacity.

Hint 2

overwrite when full advances head too, dropping the oldest element.

Editorcircular-buffer.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.