Simvik

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 0xFF00

Learn it first

More Code review for embedded C problems