Simvik

Fix the dangling pointer

Repair a function that returns the address of a local array. An easy embedded C problem (Pointers), run and graded in the browser.

easy · Pointers · lifetime · debugging

This function compiles, and on a real board it even appears to work until some other function reuses the stack. Run it to see what the simulator reports.

Fix it without changing the signature, so that the returned pointer stays valid for the life of the program and every call returns the same address.

Starter code

const uint8_t *default_config(void) {
  uint8_t config[4] = { 0x01, 0x20, 0x00, 0x7F };
  return config;
}

Example tests

The data is readable after the call

const uint8_t *cfg = default_config();
printf("%02X %02X %02X %02X\n", cfg[0], cfg[1], cfg[2], cfg[3]);

Expected output:

01 20 00 7F

Still valid after other calls

const uint8_t *cfg = default_config();
char scratch[32];
snprintf(scratch, sizeof scratch, "%d %d %d", 1, 2, 3);
printf("%02X %02X\n", cfg[1], cfg[3]);

Expected output:

20 7F

Learn it first

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

More Pointers problems