This project is a minimalist implementation of a custom memory allocator, providing core functions like malloc, calloc, realloc, and free for Linux systems. Its goal is to offer a practical understanding of virtual memory management, fragmentation techniques, and system call optimization.
The allocator manages memory using a linked list of memory blocks (struct block_meta) and leverages specific Linux system calls:
brk/sbrk: Used for small heap allocations (below theMMAP_THRESHOLD).mmap/munmap: Used for large allocations (equal to or greater thanMMAP_THRESHOLD).- 8-byte Alignment: All allocations and metadata structures are 8-byte aligned for efficiency and portability on 64-bit systems.
- Heap Preallocation: The first small allocation triggers a large 128 KiB allocation to reduce subsequent
brk/sbrkcalls. - Best Fit Strategy: When searching for free memory, the smallest available free block that can satisfy the request is chosen.
- Coalescing: Adjacent free blocks are merged (in
os_freeandos_realloc) to reduce external fragmentation. - Splitting: Large free blocks are split to match the requested size, turning the remainder into a new free block to reduce internal fragmentation.
- In-Place
realloc:os_reallocattempts to expand the block in place on the heap (including by coalescing with free neighbors) before moving the data.
Every allocated memory zone is preceded by its metadata structure, which is also 8-byte aligned.
// Block metadata definition
struct block_meta {
size_t size;
int status; // STATUS_FREE, STATUS_ALLOC, STATUS_MAPPED
struct block_meta *prev;
struct block_meta *next;
};