Simvik

Handles that catch stale use

Hand out handles that carry a generation, so a handle to a freed slot is rejected. A medium embedded C problem (Embedded C code patterns), run and graded in…

medium · Embedded C code patterns · patterns · handles · pools

Drivers often give callers an opaque handle instead of a pointer. A plain index has a danger: after a slot is freed and reused, an old handle silently refers to the new owner. Adding a generation counter fixes this.

A handle is a uint16_t: the slot index (0 to 7) in the low 8 bits, and the slot's generation in the high 8 bits. Write:

  • h_open(): take the lowest free slot, and return its handle with the slot's current generation; return 0xFFFF if all slots are in use,
  • h_valid(h): true only if the slot is in use and its generation matches the handle's,
  • h_close(h): if the handle is valid, free the slot and increment its generation (wrapping at 255), so every old handle to it becomes invalid; return whether it was valid.

Keep the pool in static arrays.

Starter code

static bool in_use[8];

uint16_t h_open(void) {
  for (int i = 0; i < 8; i++) if (!in_use[i]) { in_use[i] = true; return (uint16_t)i; }
  return 0xFFFF;
}

bool h_valid(uint16_t h) { return (h & 0xFF) < 8 && in_use[h & 0xFF]; }

bool h_close(uint16_t h) {
  if (!h_valid(h)) return false;
  in_use[h & 0xFF] = false;
  return true;
}

Example tests

Open and close

uint16_t a = h_open(), b = h_open();
printf("0x%04X 0x%04X %d %d\n", a, b, h_valid(a), h_valid(b));
printf("%d %d\n", h_close(a), h_valid(a));

Expected output:

0x0000 0x0001 1 1
1 0

A stale handle is rejected

uint16_t a = h_open();
h_close(a);
uint16_t b = h_open();          /* reuses the slot */
printf("a=0x%04X b=0x%04X: a valid %d, b valid %d, closing a again: %d\n", a, b, h_valid(a), h_valid(b), h_close(a));

Expected output:

a=0x0000 b=0x0100: a valid 0, b valid 1, closing a again: 0

Learn it first