A lightweight, zero-dependency custom memory allocator built from scratch in C. This project bypasses the standard library's malloc and free functions, directly requesting memory from the Linux kernel using the mmap system call.
- Zero Dependencies: Does not rely on
<stdlib.h>memory functions. - Direct Kernel Allocation: Uses
mmapfor initial heap allocation (MAP_PRIVATE | MAP_ANONYMOUS). - First-Fit Algorithm: Efficiently finds available memory blocks.
- Block Splitting: Reduces internal fragmentation by splitting large blocks into smaller, exact-fit chunks.
- Memory Coalescing: Merges adjacent free blocks during
free()to prevent external fragmentation. - Aligned Memory: Ensures memory addresses are correctly aligned (8-byte boundaries) for CPU read efficiency.
Implementing-Dynamic-Memory-Heap-allocator
┣ src
┃ ┣ allocator.c
┃ ┗ allocator.h
┣ Makefile
┣ README.md
┗ main.c
src/allocator.h: The public API and Block Header structure.src/allocator.c: The core logic handling memory blocks, splitting, and coalescing.main.c: Test cases demonstrating allocation, reallocation, and freeing.
- A Linux-based OS (utilizes
<sys/mman.h>). - GCC Compiler.
- Make.
// Initialize the heap (must be called before any allocations)
void mem_init(void);
// Allocate memory
void* mem_malloc(size_t size);
// Reallocate memory to a new size
void* mem_realloc(void* ptr, size_t new_size);
// Free allocated memory
void mem_free(void* ptr);Clone the repository and use the provided Makefile:
git clone [https://github.com/abdelhalimyasser/Implementing-Dynamic-Memory-Heap-allocator.git](https://github.com/abdelhalimyasser/Implementing-Dynamic-Memory-Heap-allocator.git)
cd Implementing-Dynamic-Memory-Heap-allocator
make run-
Initialization:Requests a contiguous block of memory of64KBdirectly from the OS usingmmap. -
Metadata:Prepend a hidden BlockHeader struct to each allocated memory chunk to track itssize,is_freestatus, and thenextblock in thelinked list. -
Allocation:Traverses the linked list to find the first free block large enough. If the block is significantly larger than requested, it splits it into two blocks. -
Deallocation:Marks the block as free and immediately checks adjacent blocks to coalesce them into a single larger free block.