Simvik

Fix: reset leaves old data in the buffer

Clearing a buffer passed as a pointer clears only as many bytes as a pointer holds. An easy embedded C problem (Arrays and strings), run and graded in the…

easy · Arrays and strings · find-the-bug · sizeof · pointers · arrays

Bug report. After a reset command, buf_clear(buf, n) should set all n bytes of the buffer to zero. On the device only the first four bytes of the 32-byte receive buffer are cleared, and stale bytes from the previous message leak into the next one. Fix it by changing one line.

Starter code

void buf_clear(uint8_t *buf, size_t n) {
  memset(buf, 0, sizeof(buf));
}

Example tests

Clear a 10-byte buffer

uint8_t b[10];
memset(b, 0xAA, sizeof b);
buf_clear(b, sizeof b);
int sum = 0;
for (int i = 0; i < 10; i++) sum += b[i];
printf("%d\n", sum);

Expected output:

0

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems