Simvik

Bump allocator

Hand out aligned chunks from a static buffer. A medium embedded C problem (Buffers and data structures), run and graded in the browser.

medium · Buffers and data structures · allocator · alignment

An arena allocates by moving an offset forward and frees everything at once. It is the usual replacement for malloc during start-up.

Reserve size bytes whose offset from base is a multiple of align (a power of two): round used up to align, and if size bytes fit there, advance used past them and return their address. If they do not fit, return NULL and leave used unchanged.

Starter code

void *arena_alloc(arena_t *a, size_t size, size_t align) {
  // Round a->used up to `align`, check the space, then advance.
  return NULL;
}

Example tests

Padding for alignment

uint8_t buf[32];
arena_t a = { buf, sizeof buf, 0 };
uint8_t *p1 = arena_alloc(&a, 3, 1);
uint8_t *p2 = arena_alloc(&a, 4, 4);
printf("%d %d %u\n", (int)(p1 - buf), (int)(p2 - buf), (unsigned)a.used);

Expected output:

0 4 8

Request larger than the arena

uint8_t buf[32];
arena_t a = { buf, sizeof buf, 0 };
printf("%s %u\n", arena_alloc(&a, 40, 1) ? "ok" : "null", (unsigned)a.used);

Expected output:

null 0

Learn it first

More Buffers and data structures problems