Design and implement a simplified memory allocator with malloc(size) and free(ptr) for a fixed-size heap.
Requirements:
-
The allocator manages a contiguous memory region, such as a byte array.
-
malloc(size)
should return a pointer or offset to a block of at least
size
bytes, or fail if no suitable block exists.
-
free(ptr)
should mark a previously allocated block as reusable.
-
Start with a simple first-fit implementation that linearly scans the heap or free list and chooses the first free block large enough to satisfy the request.
-
Support block splitting when a free block is larger than requested.
-
Discuss how to handle adjacent free blocks and reduce fragmentation.
-
Then propose an optimization using a best-fit strategy: choose the smallest free block that can satisfy the allocation request, using an appropriate ordered data structure such as a heap, balanced tree, or size-indexed free list.
-
Analyze the time complexity, space overhead, and trade-offs between first-fit and best-fit allocation.