Simvik

Unique IDs from a private pool

Hand out and take back small IDs from state that only this module can see. An easy embedded C problem (Scope, linkage and storage duration), run and graded…

easy · Scope, linkage and storage duration · linkage · static · modules

A driver gives each open connection a small ID from 0 to 15. The IDs in use must be remembered between calls and must be private to the module: no other file should be able to change them.

Write id_alloc(), which returns the lowest free ID and marks it used (or -1 when all 16 are in use), and id_free(id), which releases an ID (ignore IDs out of range or not in use).

Keep the state in a static variable at file scope: it lives for the whole program but has internal linkage.

Starter code

int id_alloc(void) {
  uint16_t used = 0;               // forgotten after every call
  for (int i = 0; i < 16; i++) {
    if (!(used & (1u << i))) { used |= (uint16_t)(1u << i); return i; }
  }
  return -1;
}

void id_free(int id) {
  (void)id;
}

Example tests

Consecutive IDs

int a = id_alloc(), b = id_alloc(), c = id_alloc();
printf("%d %d %d\n", a, b, c);

Expected output:

0 1 2

A freed ID is reused

int a = id_alloc(), b = id_alloc();
id_free(a);
int c = id_alloc();
printf("%d %d %d\n", a, b, c);

Expected output:

0 1 0

Learn it first

More Scope, linkage and storage duration problems