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_putstoresv, overwriting the oldest entry when the log is full.log_readcopies the stored entries toout, 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 2Oldest 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 6Learn it first
- Buffers and data structures · Ring buffers, pools, lists and bitmaps on static memory.
More Buffers and data structures problems
- Ring buffer · Implement put and get for a fixed-size FIFO.
- Fill level from two indices · Compute how many items a FIFO holds from its head and tail.
- Fixed-size stack · Push and pop on an array-backed stack with overflow and underflow checks.
- Sorted insert into a linked list · Insert a caller-provided node into an ascending singly linked list.
- Reverse a linked list · Reverse a singly linked list in place.
- Fixed-block memory pool · Allocate and free fixed-size blocks from a static pool.
- Small priority queue · Keep pending jobs ordered by priority in a fixed array.
- Bitmap operations · Set, clear and test individual bits in a byte array.
- First free slot · Find the first zero bit in a bitmap of a given length.
- Sample history by age · Store the last few samples and read them back by how old they are.
- Bump allocator · Hand out aligned chunks from a static buffer.
- Fix: the console drops characters · A serial console echoes the wrong characters once its receive buffer wraps.
- An opaque FIFO module: fifo.h and fifo.c · Implement a byte FIFO whose layout only fifo.c knows: callers hold a pointer and use four functions.
- Bluetooth speaker: never overwrite unplayed audio · A sample ring buffer that refuses new samples when full instead of overwriting the ones not yet played.