Master the fundamental concepts of memory optimization through this focused micro-challenge.
You have read the whole brief, and the concepts above stay free on every task. Writing and running the code needs a plan.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it worksBump (arena) allocators hand out memory by advancing an offset into a preallocated block. Freeing individual objects is unsupported; reset the whole arena in one instruction. Compilers, parsers, and per-request HTTP handlers use bump pointers because allocation is a pointer add.
Request n bytes aligned to alignof(max_align_t). If the arena has space, bump offset and return the previous pointer. Otherwise grow or abort.
cLoading…
Keep the relevant documentation open while you implement. When your output disagrees with the reference, trace one failing case by hand before changing random lines.
You will implement a bump allocator and use it for thousands of short-lived objects. This exercise asks you to show allocation speed versus malloc and document the reset strategy.
A bump allocator (linear allocator) is the fastest allocator there is. It keeps one offset. alloc rounds the offset up to the requested alignment, returns it, and moves it forward. Nothing is freed individually. Instead, everything is released at once with reset, or back to a saved mark with rewind, which is ideal for per-frame or per-request scratch memory. Implement it, and detect code that keeps using memory after it was released.
cLoading…
start = round_up(top, ALIGN). If start + SIZE > capacity, print alloc NAME: out of memory (need N, M left), where N = padding + SIZE and M = capacity - top. Otherwise top = start + SIZE.alloc NAME: name in use.rewind invalidates every allocation made after its mark, and reset invalidates every allocation. use reports ok, DANGLING, or never allocated.stats reports the current use, the high-water mark, the total number of successful allocations, and the total alignment padding ever inserted.arena: 1..1048576 bytes, alloc NAME: bad size or alignment, mark: too many marks (16 at most), and rewind: no mark.cLoading…
Input:
cLoading…
Output:
cLoading…
(top + align - 1) & ~(align - 1), which only works for powers of two, so reject anything else.use checks.Hidden tests cover nested marks rewound in order, large alignments (64), zero-byte allocations, filling the arena exactly, rewind with no marks, invalid alignments, and reusing a name after a rewind.