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
-1Learn it first
- Static analysis and MISRA in practice · Warnings worth enabling, the essential type model, common MISRA findings, deviations and legacy code.
More Static analysis and MISRA in practice problems
- Fix: the energy counter loses energy · An energy meter multiplies in 32 bits and only then adds to a 64-bit total.
- Fix: the modem is not reset when it should be · A counter inside the right side of && only counts some of the time.
- Fix: turning the LED off reboots the device · A missing break makes one command fall through into the next.
- Fix: faults above 31 cannot be set or cleared · A 64-bit fault mask is updated with 32-bit shifts, and clearing one fault clears thirty-two.
- Fix: settings that say they saved, but did not · A settings save ignores the return values of the flash erase and write.
- Fix: a short frame is read past its end · A length check compares a negative int with sizeof, which converts it to a huge unsigned value.
- Make a driver function MISRA compliant · Working code that the project's MISRA checker rejects: fix every finding without changing what it does.
- No recursion, no heap · Rewrite a recursive function and a heap-using function to fit a safety-critical project's rules.
- Essential types in sensor maths · Make three small sensor functions pass MISRA's essential type rules, without changing their results.