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:
11Everything free
const uint8_t map[] = { 0x00 };
printf("%d\n", bitmap_find_free(map, 8));Expected output:
0Learn it first
- Buffers and data structures · Ring buffers, pools, lists and bitmaps on static memory.
More Buffers and data structures problems
- Ring buffer · Implement put and get for a fixed-size FIFO.
- Fill level from two indices · Compute how many items a FIFO holds from its head and tail.
- Overwriting log buffer · Keep only the most recent entries, replacing the oldest when full.
- Fixed-size stack · Push and pop on an array-backed stack with overflow and underflow checks.
- Sorted insert into a linked list · Insert a caller-provided node into an ascending singly linked list.
- Reverse a linked list · Reverse a singly linked list in place.
- Fixed-block memory pool · Allocate and free fixed-size blocks from a static pool.
- Small priority queue · Keep pending jobs ordered by priority in a fixed array.
- Bitmap operations · Set, clear and test individual bits in a byte array.
- Sample history by age · Store the last few samples and read them back by how old they are.
- Bump allocator · Hand out aligned chunks from a static buffer.
- Fix: the console drops characters · A serial console echoes the wrong characters once its receive buffer wraps.
- An opaque FIFO module: fifo.h and fifo.c · Implement a byte FIFO whose layout only fifo.c knows: callers hold a pointer and use four functions.
- Bluetooth speaker: never overwrite unplayed audio · A sample ring buffer that refuses new samples when full instead of overwriting the ones not yet played.