Simvik

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, with gcd(a, 0) == a.
  • to_hex(v, out): write v as exactly 8 upper-case hex digits and a terminator into out.

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 = 0x00000015

Learn it first

More Static analysis and MISRA in practice problems