Simvik

Fix: a crash on an empty sensor batch

The monitor faults when a batch has no samples. A medium embedded C problem (Integers and data types), run and graded in the browser.

medium · Integers and data types · find-the-bug · unsigned · size_t

Bug report. The vibration monitor hard-faults about once a day. Every crash log shows a sensor batch with no samples in it; batches with samples are always processed correctly.

total_change returns the sum of the absolute differences between consecutive samples, and 0 when there are fewer than two. Find the defect and fix it by changing one line. Run the examples to reproduce the crash.

Starter code

uint32_t total_change(const int16_t *s, size_t n) {
  uint32_t total = 0;
  for (size_t i = 0; i < n - 1; i++) {
    int d = s[i + 1] - s[i];
    total += d < 0 ? -d : d;
  }
  return total;
}

Example tests

A normal batch

int16_t s[] = {10, 15, 12, 20};
printf("%u\n", total_change(s, 4));

Expected output:

16

An empty batch

int16_t s[1] = {0};
printf("%u\n", total_change(s, 0));

Expected output:

0

Learn it first

More Integers and data types problems