Complete malloc Capstone

hard · memory, systems, 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 reuse
  • my_free(ptr) - mark blocks as free
  • my_realloc(ptr, size) - resize with data preservation
  • my_calloc(count, size) - allocate zeroed memory

Requirements

Core Functionality

  1. Block metadata: Store size, free flag, and next pointer
  2. Free list: Track all blocks in a linked list
  3. First-fit search: Find first free block that fits
  4. Block reuse: malloc → free → malloc must reuse blocks

Edge Cases

  1. malloc(0) returns NULL
  2. free(NULL) does nothing
  3. realloc(NULL, n) acts like malloc(n)
  4. realloc(p, 0) acts like free(p), returns NULL
  5. calloc detects multiplication overflow

Data Integrity

  1. Freed blocks can be reused
  2. realloc preserves existing data
  3. calloc zero-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