Complete malloc Capstone
Complete malloc: The Capstone
This is the final challenge. Build a complete memory allocator from scratch.
Your allocator must implement:
my_malloc(size)- allocate memory with free block reusemy_free(ptr)- mark blocks as freemy_realloc(ptr, size)- resize with data preservationmy_calloc(count, size)- allocate zeroed memory
Requirements
Core Functionality
- Block metadata: Store size, free flag, and next pointer
- Free list: Track all blocks in a linked list
- First-fit search: Find first free block that fits
- Block reuse:
malloc → free → mallocmust reuse blocks
Edge Cases
malloc(0)returns NULLfree(NULL)does nothingrealloc(NULL, n)acts likemalloc(n)realloc(p, 0)acts likefree(p), returns NULLcallocdetects multiplication overflow
Data Integrity
- Freed blocks can be reused
reallocpreserves existing datacalloczero-initializes memory
Testing Strategy
Your implementation will be tested with:
- Basic operations: Simple alloc/free/realloc/calloc
- Reuse verification: Ensure freed blocks are reused
- Stress tests: Many allocations in patterns
- Data integrity: Verify data survives operations
- Edge cases: NULL pointers, zero sizes, overflow
Memory Layout
┌─────────────────────────────────────────────────────────┐
│ Heap │
├───────────┬───────────┬───────────┬───────────┬─────────┤
│ Block 1 │ Block 2 │ Block 3 │ Block 4 │ ... │
│ [hdr|data]│ [hdr|data]│ [hdr|data]│ [hdr|data]│ │
│ used │ FREE │ used │ FREE │ │
└───────────┴───────────┴───────────┴───────────┴─────────┘
↑ ↑
Reusable! Reusable!
Implementation Skeleton
typedef struct block_header {
size_t size; // User data size
int free; // 1 = free, 0 = used
struct block_header *next;
} block_header_t;
block_header_t *free_list_head = NULL;
void *my_malloc(size_t size);
void my_free(void *ptr);
void *my_realloc(void *ptr, size_t size);
void *my_calloc(size_t count, size_t size);
This Is Your Moment
You've built each piece. Now put it all together.
The tests are comprehensive. Pass them all and you've built malloc.
Run tests to see results
No issues detected