Show HN: I wrote a minimal memory allocator in C

https://news.ycombinator.com/rss Hits: 15
Summary

Custom Memory Allocator A custom implementation of malloc, calloc, realloc, and free in C. Overview 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! Building Prerequisites GCC compiler Make POSIX-compliant system (Linux, macOS) because we're using sbrk() and mmap() <- won't work on Windows Quick Start make # build everything make tests # run tests make bench # run benchmark Usage Using the library in your own code Build the static library: make lib Include the header in your C file: #include "allocator.h" Compile your program with the library: gcc -I./include examples/my_program.c -L./build -lallocator -o my_program Run the compiled program ./my_program Example #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 ; } Project Structure . โ”œโ”€โ”€ 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 Notes Not thread-safe (no mutex protection) fyi: sbrk is deprecated on macOS but still functional is deprecated on macOS but still functional No defragmentation or compaction License MIT License :D Contr...

First seen: 2025-11-24 00:20

Last seen: 2025-11-24 14:21