No recursion, no heap
Rewrite a recursive function and a heap-using function to fit a safety-critical project's rules. A medium embedded C problem (Static analysis and MISRA in…
medium · Static analysis and MISRA in practice · misra · static-analysis · coding-standards · recursion · heap
Safety standards want stack and memory use that can be worked out before the device ships. Recursion makes stack depth depend on the input (MISRA Rule 17.2), and malloc can fail or fragment at run time (Rule 21.3). This project also asks for one exit at the end of each function (Rule 15.5, advisory, adopted as mandatory here).
Both functions below give the right answers. Rewrite them so the checker accepts them:
gcd(a, b): the greatest common divisor, withgcd(a, 0) == a.to_hex(v, out): writevas exactly 8 upper-case hex digits and a terminator intoout.
Starter code
uint32_t gcd(uint32_t a, uint32_t b) {
if (b == 0U) {
return a;
}
return gcd(b, a % b);
}
void to_hex(uint32_t v, char out[9]) {
char *tmp = malloc(9U);
for (int32_t i = 7; i >= 0; i--) {
tmp[i] = "0123456789ABCDEF"[v & 0xFU];
v >>= 4U;
}
tmp[8] = '\0';
strcpy(out, tmp);
free(tmp);
}Example tests
Two common divisors
show(48, 18);
show(1071, 462);Expected output:
gcd(48, 18) = 6 = 0x00000006
gcd(1071, 462) = 21 = 0x00000015Learn 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: the search that never stops · A countdown loop with an unsigned index has a condition that is always true.
- 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.
- Essential types in sensor maths · Make three small sensor functions pass MISRA's essential type rules, without changing their results.