t9nzin/memory: a custom memory allocator in C

A custom implementation of malloc, calloc, realloc and free in C.

This project implements using memory allocator from scratch sbrk for small allotments and mmap For larger allocations. This includes optimizations such as block splitting to reduce fragmentation and coalescing to merge adjacent free blocks. Please note that this is the allocator not thread-safeConcurrent calls to malloc/free/realloc will cause undefined behavior, I’ve also written a blog post (~20 min read) explaining the process behind writing this memory allocator project step by step, if that’s of interest, you can read it here!

  • gcc compiler
  • Make
  • POSIX-compliant system (Linux, macOS) because we are using sbrk() And mmap() <- will not work on Windows
make           # build everything
make tests     # run tests
make bench     # run benchmark

Using the Library in Your Code

  1. Create static library:

  2. Include headers in your C file:

  3. Compile your program with the library:

    gcc -I./include examples/my_program.c -L./build -lallocator -o my_program
  4. run compiled program

#include 
#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)
  • Fee: sbrk Obsolete on macOS but still functional
  • No defragmentation or compaction

MIT license 😀

Contributions are welcome. Please open an issue or submit a pull request.

@t9nzin

I give credit to Dan Lu for his excellent malloc() tutorial, which I enjoyed reading and served as a useful 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 would also like to thank Joshua Zhou and Abdul Fatir for reading the attached blog post for this project and giving me good feedback.



<a href

Leave a Comment