Simvik

Overwriting log buffer

Keep only the most recent entries, replacing the oldest when full. A medium embedded C problem (Buffers and data structures), run and graded in the browser.

medium · Buffers and data structures · circular-buffer · logging

A crash log should hold the most recent events, so a full buffer drops its oldest entry instead of rejecting the new one. A zero-initialised log_t is empty.

  • log_put stores v, overwriting the oldest entry when the log is full.
  • log_read copies the stored entries to out, oldest first, and returns how many there are.

Starter code

void log_put(log_t *l, uint8_t v) {
  // Write at `next`, wrap, and let count saturate at LOG_SIZE.
}

size_t log_read(const log_t *l, uint8_t *out) {
  // Copy the entries oldest first; return the number copied.
  return 0;
}

Example tests

Not yet full

log_t l = { 0 };
log_put(&l, 1); log_put(&l, 2);
dump(&l);

Expected output:

2: 1 2

Oldest entries are overwritten

log_t l = { 0 };
for (uint8_t i = 1; i <= 6; i++) log_put(&l, i);
dump(&l);

Expected output:

4: 3 4 5 6

Learn it first

More Buffers and data structures problems