Fix: the console drops characters
A serial console echoes the wrong characters once its receive buffer wraps. An easy embedded C problem (Buffers and data structures), run and graded in the…
easy · Buffers and data structures · find-the-bug · ring-buffer · off-by-one
Bug report. The debug console echoes the first sixteen typed characters correctly. After that, characters start coming back wrong: a letter from earlier in the line appears where a new one was typed.
The UART interrupt stores each received byte with rb_put, and the main loop reads it back with a rb_get that is known to be correct. Find the defect in rb_put and fix it by changing one line. Run the example to see the symptom.
Starter code
bool rb_put(rb_t *r, uint8_t b) {
if (r->count == RB_SIZE) return false;
r->buf[r->head] = b;
r->head = (r->head + 1) % (RB_SIZE + 1);
r->count++;
return true;
}Example tests
Echo a line longer than the buffer
rb_t r = {0};
echo(&r, "Hello, embedded world!");Expected output:
Hello, embedded world!Learn 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.
- Overwriting log buffer · Keep only the most recent entries, replacing the oldest when full.
- 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.
- 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.