Simvik

Fix: the receiver rejects some frames

The checksum covers one byte too many. A medium embedded C problem (Checksums and CRCs), run and graded in the browser.

medium · Checksums and CRCs · find-the-bug · checksum · off-by-one

Bug report. The receiver rejects some frames. A logic analyser shows that the length and payload bytes on the wire are correct; only the checksum byte is wrong. Frames built in a freshly zeroed buffer always pass.

frame_checksum returns the one's complement (~) of the 8-bit sum of len and the len payload bytes. Find the defect and fix it by changing one line.

Starter code

uint8_t frame_checksum(const frame_t *f) {
  uint8_t s = f->len;
  for (uint8_t i = 0; i <= f->len; i++) s += f->data[i];
  return (uint8_t)~s;
}

Example tests

A fresh frame, then the same buffer reused for a shorter one

frame_t f;
memset(&f, 0, sizeof f);
f.len = 3;
f.data[0] = 0x10; f.data[1] = 0x20; f.data[2] = 0x30;
printf("%02X\n", frame_checksum(&f));
f.len = 2;   // data[2] still holds 0x30 from the last frame
printf("%02X\n", frame_checksum(&f));

Expected output:

9C
CD

Learn it first

  • Checksums and CRCs · Detecting corruption: sums versus CRCs, CRC parameters, tables and protecting stored records.

More Checksums and CRCs problems