A custom memory allocator built in C that implements malloc and free using a doubly linked list. The project manages heap memory with sbrk/brk, supports block splitting and merging, heap expansion/shrinking, and basic thread safety, while exploring low-level memory management and OS internals.
A custom implementation of malloc() and free() built from scratch in C to explore low-level memory management, heap allocation, and operating system internals.
This project manually manages heap memory using sbrk() and brk(), maintains memory blocks through a doubly linked list, and demonstrates how memory allocators split, merge, expand, and shrink heap regions dynamically.
- Custom
mallocandfreeimplementation - Heap management using
sbrk()andbrk() - Doubly linked list based block management
- Best-fit allocation strategy
- Block splitting during allocation
- Block merging (coalescing) during free
- Heap expansion and shrinking
- Basic thread safety using a simple lock
- Memory/page inspection utilities
- Automated tests using
assert
+----------------------+
| Allocator Header |
|----------------------|
| magic bytes |
| lock |
| amount of blocks |
| amount of pages |
+----------------------+
+----------------------+
| Block Header |
|----------------------|
| marker |
| prev pointer |
| next pointer |
| length |
| in_use flag |
+----------------------+
| User Memory |
+----------------------+
- Searches for the smallest available free block
- Splits blocks if extra space remains
- Expands the heap using
sbrk()if required - Returns a pointer to usable memory
- Marks the block as free
- Merges adjacent free blocks
- Shrinks the heap when possible
- Clears released memory
- Heap memory management
- Program break (
brk/sbrk) - Virtual memory pages
- Pointer arithmetic
- Raw memory traversal
- Linked lists
- Memory fragmentation
- Thread synchronization
- Linux process memory maps
allocator.c
│
├── an_malloc() -> custom malloc implementation
├── an_free() -> custom free implementation
├── add_used_block() -> allocation logic
├── reduce_heap_size_if_possible()
├── Heap/Page Experiments
└── Automated Tests
gcc allocator.c -o allocator
./allocator
char *ptr = (char *)an_malloc(100); ptr[0] = 'A'; an_free(ptr);
- Basic allocation tests
- Large allocation tests
- Block splitting tests
- Block merging tests
- Heap growth/shrinking tests
- Complex allocation/free scenarios
This allocator is designed for educational purposes and is not production-ready.
Missing features include:
- Proper memory alignment
callocrealloc- Advanced synchronization primitives
- Double-free protection
- Optimized allocation bins
- Metadata protection
This project was built to better understand:
- How
malloc()andfree()work internally - How operating systems manage heap memory
- Low-level systems programming concepts
- Memory safety and fragmentation
- Runtime allocator design