Simvik

Review: sizeof on an array parameter

A function meant to clear a receive buffer only clears its first few bytes. An easy embedded C problem (Code review for embedded C), run and graded in the…

easy · Code review for embedded C · find-the-bug · code-review · sizeof · arrays

Review comment. "buf is a parameter, so despite the [RX_SIZE] in the declaration it is a pointer, and sizeof buf is the size of a pointer, not of the buffer. Stale bytes from the previous frame survive the clear. The compiler warns about this with -Wsizeof-array-argument."

Fix rx_clear by changing one line, so it clears all RX_SIZE bytes.

Starter code

void rx_clear(uint8_t buf[RX_SIZE]) {
  memset(buf, 0, sizeof buf);
}

Example tests

Clear a full buffer

uint8_t rx[RX_SIZE];
memset(rx, 0xAA, sizeof rx);
rx_clear(rx);
show(rx);

Expected output:

0 stale bytes

Learn it first

More Code review for embedded C problems