Simvik

Fix: the search that never stops

A countdown loop with an unsigned index has a condition that is always true. An easy embedded C problem (Static analysis and MISRA in practice), run and…

easy · Static analysis and MISRA in practice · find-the-bug · static-analysis · misra · unsigned · infinite-loop

Analyser finding (suppressed). "Rule 14.3: controlling expression i >= 0 is invariantly true." It was suppressed with the note "the loop returns before then".

last_nonzero returns the index of the last non-zero byte, or -1 if there is none. On an all-zero buffer it runs off the front of the array. Fix it by changing one line.

Starter code

int last_nonzero(const uint8_t *p, uint8_t n) {
  for (uint8_t i = n - 1; i >= 0; i--) if (p[i] != 0) return i;
  return -1;
}

Example tests

A byte near the end, then none at all

uint8_t a[6] = { 1, 0, 7, 0, 0, 0 };
find(a, 6);
uint8_t z[4] = { 0 };
find(z, 4);

Expected output:

2
-1

Learn it first

More Static analysis and MISRA in practice problems