Simvik

First free slot

Find the first zero bit in a bitmap of a given length. A medium embedded C problem (Buffers and data structures), run and graded in the browser.

medium · Buffers and data structures · bitmap · allocator

An allocator marks used slots with a 1 bit. Return the index of the first 0 bit among the first nbits bits of map, or -1 if they are all set.

nbits need not be a multiple of 8: bits beyond it in the last byte do not exist and must be ignored.

Starter code

int bitmap_find_free(const uint8_t *map, size_t nbits) {
  // Index of the first clear bit below nbits, or -1.
  return -1;
}

Example tests

Free slot in the second byte

const uint8_t map[] = { 0xFF, 0x07 };
printf("%d\n", bitmap_find_free(map, 16));

Expected output:

11

Everything free

const uint8_t map[] = { 0x00 };
printf("%d\n", bitmap_find_free(map, 8));

Expected output:

0

Learn it first

More Buffers and data structures problems