ft_malloc
Custom dynamic memory allocator implementing malloc, free, and realloc as a shared library (libft_malloc_$HOSTTYPE.so).
42 School project.
Build
make # build lib/libft_malloc_$HOSTTYPE.so + symlink
make test # build & run tests
make clean # remove object files
make fclean # full clean (library, Libft, tests)
make re # fclean + all
Usage
The library is loaded at runtime via LD_PRELOAD, which instructs the Linux
dynamic linker to load the specified shared library before any other,
including libc. Any symbols it exports (such as malloc, free, realloc)
override the default ones. This makes it a drop-in replacement with no
recompilation needed:
LD_PRELOAD=./lib/libft_malloc.so ./my_program
Every call to malloc, free, or realloc inside my_program (and any
library it uses) will go through ft_malloc instead of the system allocator.
API
| Function | Description |
|---|---|
void *malloc(size_t size) |
Allocate size bytes |
void free(void *ptr) |
Release a previously allocated block |
void *realloc(void *ptr, size_t size) |
Resize a block to size bytes |
void show_alloc_mem(void) |
Print all zones and allocations to stdout |
Architecture
Allocations are divided into three categories:
| Category | Size range | Strategy |
|---|---|---|
| TINY | 1 -- 128 bytes | Pre-allocated zone (fits 100+ allocations) |
| SMALL | 129 -- 1024 bytes | Pre-allocated zone (fits 100+ allocations) |
| LARGE | 1025+ bytes | Individual mmap per allocation |
TINY and SMALL zones are page-aligned regions obtained via mmap. New zones
are allocated on demand when the current one is full. LARGE allocations each
get their own mmap region and are released individually via munmap.
All returned pointers are 16-byte aligned.
Testing
AddressSanitizer (ASan) cannot be used to test this allocator. ASan intercepts
malloc/free itself and expects specific allocator metadata (redzones,
quarantine zones) that a custom allocator does not provide. The two
implementations would conflict. Since allocations go through mmap, they also
bypass ASan's shadow memory tracking entirely.
Alternatives for catching bugs:
- Valgrind — operates at the binary level without replacing malloc, so it
can detect issues in the allocator's own internal logic.
- Custom tests — targeted checks for write-after-free, double free, boundary
writes, and stress scenarios.
- show_alloc_mem() — inspect zone and chunk state visually after
operations.
