aboutsummaryrefslogtreecommitdiffstats
path: root/README.md
blob: ef21ed771bb3fb7812ee8092aafd98ff1cae56fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# ft_malloc

Custom dynamic memory allocator implementing `malloc`, `free`, and `realloc` as a shared library (`libft_malloc_$HOSTTYPE.so`).

42 School project.

## Build

```bash
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:

```bash
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.