Design a Fixed-Heap Memory Manager
Data Structure DesignModel answerLast updated
Build malloc and free over a fixed byte array, comparing allocation strategies and analyzing fragmentation trade-offs.
You are building a memory manager that operates over a single contiguous buffer of fixed size. The manager exposes two operations:
allocate(bytes)— returns a pointer to a region of at leastbytesusable space, or null if no suitable region existsdeallocate(ptr)— marks a previously allocated region as available for reuse
The manager receives its memory up front and cannot request additional memory later. All bookkeeping must happen within the provided buffer.
Your task is to design and implement this manager, starting with a correct baseline and progressing to optimized variants. For each variant, analyze time and space complexity and discuss the trade-offs.
Requirements
- The buffer is a fixed-size contiguous region initialized once
- Returned pointers must be aligned to 8-byte boundaries
- Assume single-threaded execution for the core design
- You may assume
deallocatereceives valid pointers from priorallocatecalls, but discuss how you would detect misuse
Questions to Consider
Before designing, clarify:
- What is the typical allocation size distribution?
- What matters more: allocation speed or memory utilization?
- How should edge cases like zero-byte requests be handled?
- Should the design prevent or detect double-free errors?
Part 1: Linear-Scan Allocator
Implement allocate and deallocate using a linear scan: walk through memory until you find the first available region large enough. When a region is larger than needed, divide it so the unused portion remains available.
Describe your block metadata layout, explain how alignment is enforced, and state the time complexity of each operation.
Part 2: Adjacent-Block Merging
Extend deallocate to merge newly-freed regions with adjacent free neighbors. Explain the difference between external and internal fragmentation, and describe how merging addresses one but not the other.
Part 3: Smallest-Fit Strategy
Modify the allocator to choose the smallest free region that satisfies each request, rather than the first one encountered. Select a data structure that makes this efficient.
Explain why a standard min-heap is insufficient for this query, and justify your chosen structure. Describe how block splitting and merging interact with this structure.
Part 4: Strategy Comparison
Compare the linear-scan and smallest-fit approaches across:
- Allocation and deallocation cost
- Metadata overhead
- Long-term fragmentation behavior
Identify workloads where each strategy is preferable.
Hints
Hint 1
Consider what metadata each block needs to store and where that metadata lives relative to the returned pointer
Hint 2
Merging adjacent blocks requires walking backward and forward from the freed block — think about what information enables constant-time neighbor lookups
Hint 3
A query for 'smallest block ≥ X bytes' is a range query, not a global minimum — choose a structure that supports efficient lower-bound search
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Block Layout and Metadata
Each memory region consists of a header followed by payload space. The header stores:
- Size of the payload area (or total block size, chosen consistently)
- Allocation status (free or in-use)
- Optional: pointer or offset to the next block in a free list
For 8-byte alignment, round all payload sizes up to multiples of 8. The header itself should be a multiple of 8 bytes to keep the payload aligned.
Example layout:
[ Header: 8 bytes ][ Payload: N bytes (aligned) ]
When allocate returns a pointer, it points to the start of the payload, not the header. To access metadata during deallocate, subtract the header size from the provided pointer.
A minimum block size (e.g., 16 payload bytes) prevents splitting from creating unusably small fragments.
Part 1: Linear-Scan Allocator
Allocation: Start at the beginning of the buffer. Walk through each block, checking its status and size. When you find a free block with size ≥ request:
- If the leftover space (after allocation + header) is ≥ minimum block size, split: mark the first portion allocated, create a new free block header in the remainder
- Otherwise, allocate the entire block (internal fragmentation in this case)
- Return a pointer to the payload
Deallocation: Given a pointer, compute the header location, mark the block free.
Complexity:
allocate: O(n) where n is the number of blocks, since we scan linearlydeallocate: O(1), just marking a status bit
Space overhead: One header per block, plus any internal fragmentation from blocks that cannot be split.
Part 2: Adjacent-Block Merging
External vs. internal fragmentation:
- External: Free space exists but is scattered in pieces too small to satisfy requests
- Internal: Allocated blocks contain unused padding because the allocator rounded up or couldn't split
Merging strategy: When a block is freed, check the physical neighbors:
- Previous neighbor: If headers store total block size, you can walk backward from the current header by subtracting the previous block's size. Check if that block is free; if so, merge by updating the previous block's size to include the current block.
- Next neighbor: The next block starts immediately after the current block's payload. Check its status; if free, extend the current block's size to absorb it.
Perform both checks in sequence (order matters: merge with previous first, then check next, or vice versa, but do both).
Why this helps: Merging reduces external fragmentation by consolidating adjacent gaps. It does not eliminate fragmentation caused by interleaved allocations and deallocations, and it does not reduce internal fragmentation.
Complexity: Merging is O(1) per freed block, assuming headers contain size information for constant-time neighbor lookup. deallocate becomes O(1) with merging.
Part 3: Smallest-Fit Strategy
Goal: Choose the free block whose size is closest to the request, minimizing leftover space per allocation.
Why a min-heap doesn't work: A min-heap keyed by size returns the globally smallest element. We need the smallest block that is at least the requested size — a lower-bound or successor query. Extracting this from a min-heap requires scanning elements until we find one large enough, which is not efficient.
Better structure: Use a balanced binary search tree (e.g., red-black tree, AVL tree) keyed by block size. The tree supports O(log k) lower-bound queries, where k is the number of free blocks.
Alternatively, maintain segregated free lists: one list per size class (e.g., 16–31 bytes, 32–63 bytes, etc.). To allocate, find the smallest class that fits, then scan that list. This reduces the search space but adds bookkeeping overhead.
Dual indexing: The physical layout of blocks (for merging) is a linked list or implicit array by address. The size-ordered tree is a second index. Every split and merge must update both:
- Split: Remove the chosen block from the tree, insert two smaller blocks (one allocated, one free, so only the free part goes back in the tree)
- Merge: Remove the blocks being merged from the tree, insert the merged block
Complexity with tree:
allocate: O(log k) to find the block, O(log k) to remove it, O(log k) to insert the split remainder = O(log k)deallocatewith merging: O(1) to find neighbors physically, O(log k) per tree removal/insertion for merging = O(log k)
Part 4: Strategy Comparison
| Aspect | Linear Scan (First-Fit) | Smallest-Fit with Tree |
|---|---|---|
| Allocation cost | O(n) | O(log k) |
| Deallocation cost | O(1) | O(log k) |
| Metadata overhead | One header per block | Header + tree node per free block |
| Fragmentation | Leaves large blocks intact early, clusters small gaps near the start | Minimizes waste per allocation but can create many tiny unusable slivers |
Key insight: Smallest-fit optimizes each individual allocation but doesn't guarantee better long-term utilization. By always choosing the tightest fit, it can fragment large blocks into increasingly small pieces. First-fit, by contrast, tends to leave larger blocks untouched until needed, which can be better for mixed workloads.
When to prefer each:
- First-fit: Simple, low overhead, acceptable for workloads with similar-sized allocations or when allocation latency must be bounded by block count
- Smallest-fit: Better memory utilization when allocation sizes vary widely and allocation speed is less critical than packing efficiency; however, requires careful minimum-split thresholds to avoid excessive fragmentation
Thread safety note: Both strategies require locking around shared structures (the free list or tree). First-fit's simpler structure may have lower contention, but that depends on lock granularity and workload.
Common Mistakes
- Forgetting alignment padding and returning misaligned pointers
- Not accounting for header size when computing remaining space for splitting
- Merging logic that only checks one neighbor or checks in the wrong order, leaving adjacent free blocks
- Claiming best-fit always reduces fragmentation, when it can actually worsen it
- Using a min-heap for smallest-fit without recognizing the query mismatch
- Forgetting to update the size-ordered index during splitting and merging