Implement a memory allocator with malloc/free
OpenAISoftware Engineer · Technical ScreenLast updated
This question evaluates understanding of memory allocator concepts including malloc/free semantics, contiguous allocation, fragmentation handling, coalescing of adjacent free blocks, pointer validation, and data-structure choices for efficient allocation.
Problem
You are implementing a simplified memory allocator over a contiguous memory region.
Initialize the allocator with a fixed total size:
allocator(totalSize)creates an allocator that manages bytes indexed from0tototalSize-1.
Implement two operations:
-
malloc(size) -> pointer -
Allocates a contiguous block of
sizebytes. -
Returns a
pointerrepresenting the allocated block (you may define this as an integer start index, or an opaque handle that can later be passed tofree). -
If no contiguous block of at least
sizebytes is available, return a null/invalid pointer (e.g.,-1ornull). -
free(pointer) -> bool -
Frees the block previously returned by
malloc. -
Returns
trueif the pointer was valid and the block was freed, otherwise returnsfalse(e.g., double-free or unknown pointer).
Requirements / Clarifications
- The allocator must support many interleaved
mallocandfreecalls. - Freed space should become available for future allocations.
- You must correctly handle merging/coalescing of adjacent free blocks to reduce fragmentation.
- Discuss (and aim for) better-than-linear performance per operation if possible (e.g., around (O(\log n)) for finding a suitable free block).
Example (one possible interpretation)
allocator(10)p1 = malloc(3)might return0(allocates[0..2])p2 = malloc(4)might return3(allocates[3..6])free(p1)frees[0..2]p3 = malloc(2)might return0(reuses part of[0..2])
What to deliver
Explain and implement the data structures and algorithms needed to support malloc and free efficiently, including coalescing and pointer validation.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.