Simvik

Review: strncpy does not always terminate

A setter copies a name with strncpy, and a long name leaves the field without a terminator. An easy embedded C problem (Code review for embedded C), run and…

easy · Code review for embedded C · find-the-bug · code-review · strings · buffer-overflow

Review comment. "strncpy writes no '\0' when the source is as long as the field or longer. An 8-character name leaves name unterminated, and the next printf("%s") runs on into unit. Long names should be cut to 7 characters and terminated."

Fix set_name by changing (or adding) one line.

Starter code

void set_name(channel_t *c, const char *name) {
  strncpy(c->name, name, sizeof c->name);
}

Example tests

A short name, then one exactly 8 characters long

show("temp");
show("pressure");

Expected output:

name=temp unit=kPa
name=pressur unit=kPa

Learn it first

More Code review for embedded C problems