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
CDLearn it first
- Checksums and CRCs · Detecting corruption: sums versus CRCs, CRC parameters, tables and protecting stored records.
More Checksums and CRCs problems
- CRC-32 · Compute the CRC-32 used by Ethernet, zip and PNG, bit by bit.
- A table-driven CRC-16 · Build a 256-entry table once, then compute CRC-16/CCITT a byte at a time.
- Load the newest valid settings · Choose between two settings records by magic, CRC and a wrapping sequence number.
- Fix: our CRC matches the wrong tool · A CRC-16 routine has the right polynomial and the wrong initial value.
- Greenhouse: trust only good settings · Decide at start-up whether the settings read back from EEPROM can be used.