Review: blocks got bigger than the loop counter
A checksum loop uses a uint8t index, and the block size was raised past 255. 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 · integer-types · infinite-loop
Review comment. "Flash blocks are now 512 bytes, but block_sum counts with a uint8_t. It wraps from 255 to 0 and i < len is then always true, so the device hangs on the first full block."
Fix block_sum by changing one line.
Starter code
uint16_t block_sum(const uint8_t *p, size_t len) {
uint16_t s = 0;
for (uint8_t i = 0; i < len; i++) s = (uint16_t)(s + p[i]);
return s;
}Example tests
A small block, then a full one
sum(16);
sum(512);Expected output:
16 bytes: sum 0x0358
512 bytes: sum 0xFF00Learn it first
- Code review for embedded C · What to look for in firmware changes, how to comment, and what to leave to tools.
More Code review for embedded C problems
- Review: a length from the packet is trusted · A message decoder copies as many bytes as the packet says, into a fixed-size buffer.
- Review: an error path keeps the bus lock · After one failed sensor read, every later read on the shared bus deadlocks.
- Review: sizeof on an array parameter · A function meant to clear a receive buffer only clears its first few bytes.
- Review: a timeout that breaks after 49 days · A deadline check adds to a 32-bit millisecond tick, which wraps.
- Review: the ring buffer grew to 100 bytes · A change resized a ring buffer, but its index wrap still uses a bit mask.
- Review: the sensor's temperature is read in the wrong byte order · A driver copies a big-endian signed field straight into a little-endian int16_t.
- Review: strncpy does not always terminate · A setter copies a name with strncpy, and a long name leaves the field without a terminator.