Skip to content

hlefevregit/ft_malloc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 

Repository files navigation

🧠 ft_malloc - Custom Memory Allocator

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).

✨ Caractéristiques

📦 Fonctions implémentées

  • 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

🎯 Fonctionnalités clés

  • 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

📁 Architecture des fichiers

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

🏗️ Structure des données

t_block - Métadonnée de bloc

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;

t_heap - Zone mmap

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;

🔧 Compilation et utilisation

Compiler la bibliothèque

make        # Compile et crée libft_malloc.so

Lancer les tests

make run    # Compile et exécute tous les tests (44 tests)

Utiliser la librairie

# 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_programme

Nettoyage

make clean    # Supprime les fichiers .o
make fclean   # Supprime tous les fichiers générés
make re       # Recompile tout

🧪 Suite de tests (44 tests)

Catégories de tests

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

Exécution des tests

$ 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

💻 Exemple d'utilisation

#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 ./test

🎨 Affichage de la mémoire allouée

La 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

🔍 Détails d'implémentation

✍️ Alignement 16 bytes

  • Tous les blocs retournés sont alignés sur 16 bytes
  • La structure t_heap est padée à 32 bytes pour garantir l'alignement
  • Macro ALIGN16(x) : ((x + 15) & ~15)

🔗 Coalescing (fusion de blocs libres)

Avant: [LIBRE][LIBRE][UTILISÉ]
↓
Après: [LIBRE + LIBRE][UTILISÉ]

Réduit la fragmentation et optimise la mémoire.

💾 Organisation mémoire

Zone mmap (page-aligned):
┌─────────────┬──────────┬─────────┬─────────┐
│  t_heap     │  t_block │ données │ ...     │
│  (32 bytes) │  (48b)   │         │         │
└─────────────┴──────────┴─────────┴─────────┘

🎯 Stratégie d'allocation

  1. TINY/SMALL : First-fit (premier bloc libre assez grand)
  2. LARGE : Allocation directe avec mmap()
  3. Réallocation : En place si possible, sinon copie+free

📊 Performances

  • Allocation : O(n) en nombre de zones
  • Libération : O(1)
  • Coalescing : O(1)
  • Fragmentation : Minimisée par coalescing automatique

🛠️ Configuration

É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 SMALL

🎨 Makefile avec couleurs

Le 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)

📝 Notes d'implémentation

Compatibilité

  • ✅ Linux 64-bit
  • ✅ macOS (avec ajustements LD_PRELOAD)
  • ✅ Compilateur GCC/Clang

Limite du projet

  • ⚠️ Non thread-safe (pas de mutex)
  • ⚠️ Pas d'optimisation MMU
  • ⚠️ Allocations petites < alignement non optimisées

🎓 Apprentissages

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

📜 Licence

Projet pédagogique - École 42


Créé par : Hugo Date : Avril 2026 Langage : C99 Norme : 42 School (French Englobing Standard)

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors