- Explore the fundamentals of memory management by implementing custom versions of
malloc(),calloc(),realloc(), andfree(). - Utilize memory management syscalls in Linux:
brk(),mmap(), andmunmap(). - Analyze and optimize memory allocation performance and reduce fragmentation.
This project involves building a minimalistic memory allocator to manually manage virtual memory. The goal is to create a reliable library that supports explicit allocation, reallocation, and initialization of memory, while optimizing memory usage and reducing fragmentation.
The project is organized as follows:
src/contains the implementation of the memory allocator.tests/contains test cases and scripts to verify the functionality.utils/includesosmem.hfor the library interface,block_meta.hfor metadata structures, and aprintf()implementation that does not use the heap.
The test suite dynamically links with the library (libosmem.so) and verifies correctness by comparing syscall sequences with reference outputs.
-
void *os_malloc(size_t size)Allocates
sizebytes and returns a pointer to the allocated memory. Small allocations usebrk()while larger chunks usemmap(). Memory is uninitialized. Passing0returnsNULL. -
void *os_calloc(size_t nmemb, size_t size)Allocates memory for an array of
nmembelements ofsizebytes each. Small allocations usebrk(), larger ones usemmap(), and memory is zero-initialized. Passing0for either parameter returnsNULL. -
void *os_realloc(void *ptr, size_t size)Resizes the memory block at
ptrtosizebytes. The block is expanded in-place if possible; otherwise, a new block is allocated and data is copied. PassingNULLbehaves likeos_malloc(size). Passing0behaves likeos_free(ptr). -
void os_free(void *ptr)Frees memory previously allocated with
os_malloc(),os_calloc(), oros_realloc(). Memory is marked as free for reuse;munmap()is used for mapped blocks.
- Memory blocks are tracked using a doubly linked list (
struct block_meta) and aligned to 8 bytes. - The allocator supports block splitting to reduce internal fragmentation and block coalescing to reduce external fragmentation.
- The best-fit strategy is used to select free blocks for allocation.
- Heap preallocation (e.g., 128 KB) reduces the number of syscalls for small allocations.
- Error handling is included for all syscalls.
- Build the library (
libosmem.so) usingmakeinsrc/. - Automated tests verify allocation correctness, block reuse, splitting, coalescing, and realloc behavior.
- Memory leaks and system call correctness are checked using scripts based on
ltrace.