Simvik

Fixed-block memory pool

Allocate and free fixed-size blocks from a static pool. A hard embedded C problem (Buffers and data structures), run and graded in the browser.

hard · Buffers and data structures · allocator · pool

A pool of equal-sized blocks gives constant-time allocation with no fragmentation, which is why RTOSes offer it in place of malloc. A zero-initialised pool_t has every block free.

  • pool_alloc returns the lowest-numbered free block and marks it used, or returns NULL when none is free.
  • pool_free releases a block and returns true. It returns false, and changes nothing, if block is not the start address of a block in this pool or the block is not currently allocated.

Starter code

void *pool_alloc(pool_t *p) {
  // Return the first free block, or NULL.
  return NULL;
}

bool pool_free(pool_t *p, void *block) {
  // Validate the pointer before trusting it.
  return false;
}

Example tests

Blocks are handed out in order

pool_t p = { 0 };
void *a = pool_alloc(&p), *b = pool_alloc(&p);
printf("%d %d\n", idx(&p, a), idx(&p, b));

Expected output:

0 1

The pool runs out

pool_t p = { 0 };
for (int i = 0; i < 5; i++) printf("%d ", idx(&p, pool_alloc(&p)));
printf("\n");

Expected output:

0 1 2 3 -1

Learn it first

More Buffers and data structures problems