Simvik

Fix: the display shows garbage

A formatting function returns a pointer to its own local buffer. An easy embedded C problem (Pointers), run and graded in the browser.

easy · Pointers · find-the-bug · dangling-pointer · stack · static

Bug report. fmt_temp(tenths) formats a temperature given in tenths of a degree, such as 215 as 21.5 C, for the display. Sometimes the display shows the right text and sometimes garbage, depending on what ran just before. Fix it by changing one line. The display code uses each string before calling fmt_temp again.

Starter code

const char *fmt_temp(int tenths) {
  char buf[16];
  snprintf(buf, sizeof buf, "%d.%d C", tenths / 10, tenths % 10);
  return buf;
}

Example tests

Format one value

printf("%s\n", fmt_temp(215));

Expected output:

21.5 C

Learn it first

  • Pointers · Addresses, arithmetic, const, void pointers and object lifetime.

More Pointers problems