Simvik

Fix: long device names corrupt the status page

A name that fills its buffer has no terminator. A medium embedded C problem (Arrays and strings), run and graded in the browser.

medium · Arrays and strings · find-the-bug · strncpy · strings

Bug report. The status page shows device names correctly until someone gives a sensor a name of eight characters or more. Then the page prints the name followed by junk, or the firmware faults.

device_set_name stores a name, cutting it short if it does not fit. d->name must always end with a terminating '\0'. Find the defect and fix it by changing one line (adding a line counts as one change). Run the example to see the fault.

Starter code

void device_set_name(device_t *d, const char *name) {
  strncpy(d->name, name, sizeof d->name);
}

Example tests

A short name, then a long one

device_t d = { "", 0x41 };
device_set_name(&d, "pump");
printf("[%s]\n", d.name);
device_set_name(&d, "humidity-sensor");
printf("[%s]\n", d.name);

Expected output:

[pump]
[humidit]

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems