A custom implementation of malloc, calloc, realloc, and free in C.
This project implements a memory allocator from scratch using sbrk for small allocations and mmap for large allocations. It includes optimizations like block splitting to reduce fragmentation and coalescing to merge adjacent free blocks. Please note that this allocator is not thread-safe. Concurrent calls to malloc/free/realloc will cause undefined behavior. I've also written a blog post (~20 minute read) explaining step by step the process behind writing this memory allocator project, if that's of interest, you can read it here!
- GCC compiler
- Make
- POSIX-compliant system (Linux, macOS) because we're using
sbrk()andmmap()<- won't work on Windows
make # build everything
make tests # run tests
make bench # run benchmark-
Build the static library:
-
Include the header in your C file:
-
Compile your program with the library:
gcc -I./include examples/my_program.c -L./build -lallocator -o my_program
-
Run the compiled program
#include <stdio.h>
#include "allocator.h"
int main() {
int *arr = malloc(10 * sizeof(int));
if (arr == NULL) {
return 1;
}
for (int i = 0; i < 10; i++) {
arr[i] = i;
}
arr = realloc(arr, 20 * sizeof(int));
free(arr);
return 0;
}.
├── Makefile
├── README.md
├── examples
│ └── my_program.c # an example program using implemented malloc()
├── include
│ └── allocator.h # header file w/ function declarations
├── src
│ └── allocator.c # allocator
└── tests
├── benchmark.c # performance benchmarks
├── test_basic.c # basic functionality tests
└── test_edge_cases.c # edge cases and stress tests
- Not thread-safe (no mutex protection)
- fyi:
sbrkis deprecated on macOS but still functional - No defragmentation or compaction
MIT License :D
Contributions are welcome. Please open an issue or submit a pull request.
I credit Dan Luu for his fantastic malloc() tutorial which I greatly enjoyed reading and served as a helpful reference for this project. If you would like to take a look at his tutorial (which I highly recommend), you can find it here.
I'd also like to thank Joshua Zhou and Abdul Fatir for reading over and giving me great feedback on the accompanying blog post for this project.