Une implémentation complète d'un allocateur mémoire personnalisé en C, mimant les fonctionnalités de malloc(), free() et realloc(). Ce projet implémente la gestion dynamique de la mémoire via mmap() avec support de trois catégories de blocs (TINY, SMALL, LARGE).
- ✅
malloc(size_t size)- Alloue de la mémoire - ✅
free(void *ptr)- Libère la mémoire allouée - ✅
realloc(void *ptr, size_t size)- Réalloue et redimensionne la mémoire
-
Allocation multi-zones :
- 🟢 TINY : 1-128 bytes (100 blocs par zone)
- 🔵 SMALL : 129-1024 bytes (100 blocs par zone)
- 🔴 LARGE : > 1024 bytes (allocation directe)
-
Optimisations mémoire :
- ✨ Fusion des blocs libres voisins (coalescing)
- 📏 Alignement 16 bytes de tous les pointeurs retournés
- 🔄 Réutilisation des blocs libérés
-
Gestion avancée de realloc :
realloc(NULL, size)≡malloc(size)realloc(ptr, 0)≡free(ptr)- Extensibilité en place si possible
- Copie de données lors de réallocation ailleurs
ft_malloc/
├── src/
│ ├── malloc.h # Headers et structures principales
│ ├── malloc.c # Helpers et fonctions utilitaires
│ ├── malloc_alloc.c # Implémentation de malloc()
│ ├── malloc_free.c # Implémentation de free()
│ ├── malloc_realloc.c # Implémentation de realloc()
│ ├── utils.c # show_alloc_mem() - affichage mémoire
│ └── main.c # Suite de tests colorisée (44 tests)
├── Makefile # Build avec couleurs
├── libft_malloc.so # Bibliothèque dynamique compilée
└── README.md # Ce fichier
typedef struct s_block {
size_t size; // Taille allouée (alignée 16)
size_t free; // Flag: 0=utilisé, 1=libre
struct s_block *next; // Bloc suivant
struct s_block *prev; // Bloc précédent
} t_block;typedef struct s_heap {
struct s_heap *next; // Zone suivante
size_t total_size; // Taille totale de la zone
size_t free_size; // Espace libre (réservé)
size_t _padding; // Alignement 32 bytes
} t_heap;make # Compile et crée libft_malloc.somake run # Compile et exécute tous les tests (44 tests)# Avec LD_PRELOAD (remplace malloc du système)
LD_PRELOAD=./libft_malloc.so ./mon_programme
# Sur macOS
DYLD_INSERT_LIBRARIES=./libft_malloc.so DYLD_FORCE_FLAT_NAMESPACE=1 ./mon_programmemake clean # Supprime les fichiers .o
make fclean # Supprime tous les fichiers générés
make re # Recompile tout| Section | Tests | Détails |
|---|---|---|
| CAS LIMITES | 1 | malloc(0) retourne NULL |
| TINY | 9 | Allocation 1-128 bytes, alignement, écriture |
| SMALL | 6 | Allocation 129-1024 bytes, alignement |
| LARGE | 5 | Allocation > 1024 bytes, memset 1MB |
| FREE | 2 | free(NULL), réutilisation de blocs |
| REALLOC | 18 | Croissance, réduction, transitions de zones |
| STRESS | 3 | 200 allocations, absence de corruption |
Total : ✅ 44/44 tests passent
$ make run
[TEST] Building test binary
✓ Test binary compiled: test_malloc
Running tests...
╔══════════════════════════════╗
║ Tests malloc custom (ft_m) ║
╚══════════════════════════════╝
=== CAS LIMITES ===
✓ [OK] malloc(0) retourne NULL
=== TINY (1 - 128 bytes) ===
✓ [OK] malloc(1) non NULL
✓ [OK] malloc(TINY_MAX) non NULL
...
✓ Résultat : 44 / 44 tests passés#include <stdio.h>
#include <string.h>
int main(void)
{
// Allocation simple
char *str = malloc(32);
strcpy(str, "Hello malloc!");
printf("%s\n", str);
// Réallocation croissante
str = realloc(str, 100);
strcat(str, " Extended.");
// Réallocation décroissante
char *small = realloc(str, 16);
// Libération
free(small);
return (0);
}Compiler et exécuter :
gcc -o test test.c -L. -lft_malloc -Wl,-rpath,.
LD_PRELOAD=./libft_malloc.so ./testLa fonction show_alloc_mem() affiche l'état de toute la mémoire allouée :
TINY : 0x7ED2BBB2C000
0x7ED2BBB2C040 - 0x7ED2BBB2C050 : 16 bytes
0x7ED2BBB2C060 - 0x7ED2BBB2C0A0 : 64 bytes
SMALL : 0x7ED2BBAFF000
0x7ED2BBAFF040 - 0x7ED2BBAFF0C0 : 128 bytes
LARGE : 0x7ED2BBB30000
0x7ED2BBB30040 - 0x7ED2BBB31040 : 4096 bytes
Total : 4308 bytes
- Tous les blocs retournés sont alignés sur 16 bytes
- La structure
t_heapest padée à 32 bytes pour garantir l'alignement - Macro
ALIGN16(x):((x + 15) & ~15)
Avant: [LIBRE][LIBRE][UTILISÉ]
↓
Après: [LIBRE + LIBRE][UTILISÉ]
Réduit la fragmentation et optimise la mémoire.
Zone mmap (page-aligned):
┌─────────────┬──────────┬─────────┬─────────┐
│ t_heap │ t_block │ données │ ... │
│ (32 bytes) │ (48b) │ │ │
└─────────────┴──────────┴─────────┴─────────┘
- TINY/SMALL : First-fit (premier bloc libre assez grand)
- LARGE : Allocation directe avec
mmap() - Réallocation : En place si possible, sinon copie+free
- Allocation : O(n) en nombre de zones
- Libération : O(1)
- Coalescing : O(1)
- Fragmentation : Minimisée par coalescing automatique
Éditer src/malloc.h pour ajuster :
#define TINY_MAX 128 // Limite TINY
#define SMALL_MAX 1024 // Limite SMALL
#define TINY_ZONE (...) // Taille zone TINY
#define SMALL_ZONE (...) // Taille zone SMALLLe Makefile utilise des codes couleur ANSI pour une meilleure lisibilité :
✓ [CC] Compiling source files (Bleu gras)
✓ [LD] Linking library (Bleu gras)
✓ [TEST] Building test binary (Bleu gras)
✓ ✓ Library created (Vert)
- ✅ Linux 64-bit
- ✅ macOS (avec ajustements LD_PRELOAD)
- ✅ Compilateur GCC/Clang
⚠️ Non thread-safe (pas de mutex)⚠️ Pas d'optimisation MMU⚠️ Allocations petites < alignement non optimisées
Ce projet démontre :
- 🧠 Gestion mémoire bas niveau avec
mmap() - 🔄 Structure de données linkedlist
- 💡 Algorithmes de fragmentation
- 🎯 Alignement mémoire
- 🔧 Linkage dynamique avec
LD_PRELOAD
Projet pédagogique - École 42
Créé par : Hugo Date : Avril 2026 Langage : C99 Norme : 42 School (French Englobing Standard)