Langage C/C++

Guide : calloc vs malloc – Exercices Corrigés

×

Recommandés

Quand Utiliser les Pointeurs en C ?
Les pointeurs en C sont une...
En savoir plus
Guide Complet : Pointeur de Pointeur en...
Un pointeur de pointeur (ou double...
En savoir plus
Guide : Les Tableaux en C -...
Les tableaux en langage C sont...
En savoir plus
Comment fonctionne la récursion terminale en C...
La récursion terminale en C La récursion...
En savoir plus
Structure d'un Programme en Langage C
Le langage de programmation C, développé...
En savoir plus
Cours et tutoriel du langage C /...
Ce tutoriel du langage C vous...
En savoir plus

Ce guide explique les différences entre calloc et malloc à travers des exercices pratiques corrigés. Vous apprendrez à choisir la fonction appropriée en fonction des besoins spécifiques.


1. Rappel des bases

malloc

  • Alloue un bloc de mémoire d’une taille totale spécifiée.
  • Ne l’initialise pas (valeurs indéterminées).
  • Syntaxe :
  void *malloc(size_t size);

calloc

  • Alloue de la mémoire pour un certain nombre d’éléments.
  • Initialise la mémoire allouée à zéro.
  • Syntaxe :
  void *calloc(size_t nitems, size_t size);

2. Exercices corrigés

Exercice 1 : Initialiser un tableau avec malloc

Allouez un tableau de 5 entiers avec malloc, puis initialisez-le à zéro.

Solution :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array = (int *)malloc(5 * sizeof(int));
    if (array == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Initialisation manuelle
    for (int i = 0; i < 5; i++) {
        array[i] = 0;
    }

    // Affichage
    for (int i = 0; i < 5; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    free(array);
    return 0;
}

Exercice 2 : Allouer un tableau avec calloc

Réalisez la même tâche que dans l’exercice précédent, mais utilisez calloc pour simplifier le code.

Solution :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array = (int *)calloc(5, sizeof(int));
    if (array == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Affichage : Pas besoin d'initialisation explicite
    for (int i = 0; i < 5; i++) {
        printf("%d ", array[i]); // Tous les éléments sont déjà 0
    }
    printf("\n");

    free(array);
    return 0;
}

Exercice 3 : Comparer les valeurs initiales de malloc et calloc

Allouez deux tableaux de taille 5, un avec malloc et l’autre avec calloc. Affichez leurs valeurs initiales.

Solution :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array_malloc = (int *)malloc(5 * sizeof(int));
    int *array_calloc = (int *)calloc(5, sizeof(int));

    if (array_malloc == NULL || array_calloc == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    printf("Valeurs avec malloc : ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", array_malloc[i]); // Valeurs indéterminées
    }
    printf("\n");

    printf("Valeurs avec calloc : ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", array_calloc[i]); // Toutes les valeurs sont 0
    }
    printf("\n");

    free(array_malloc);
    free(array_calloc);
    return 0;
}

Exercice 4 : Matrice avec malloc et calloc

Créez une matrice 3×3 (tableau 2D) avec :

  1. malloc : initialisez les valeurs à zéro manuellement.
  2. calloc : laissez calloc initialiser la mémoire.

Solution avec malloc :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int rows = 3, cols = 3;
    int *matrix = (int *)malloc(rows * cols * sizeof(int));
    if (matrix == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Initialisation manuelle
    for (int i = 0; i < rows * cols; i++) {
        matrix[i] = 0;
    }

    // Affichage
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i * cols + j]);
        }
        printf("\n");
    }

    free(matrix);
    return 0;
}

Solution avec calloc :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int rows = 3, cols = 3;
    int *matrix = (int *)calloc(rows * cols, sizeof(int));
    if (matrix == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Pas besoin d'initialisation : la mémoire est déjà zéro
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i * cols + j]);
        }
        printf("\n");
    }

    free(matrix);
    return 0;
}

Exercice 5 : Structures avec calloc

Déclarez une structure pour représenter une personne (nom, âge). Allouez un tableau de 3 personnes avec calloc et initialisez leurs valeurs par défaut.

Solution :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char name[50];
    int age;
} Person;

int main() {
    int n = 3;
    Person *people = (Person *)calloc(n, sizeof(Person));
    if (people == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Pas besoin d'initialiser explicitement : tous les champs sont déjà zéro
    for (int i = 0; i < n; i++) {
        printf("Personne %d : Nom = '%s', Âge = %d\n", i + 1, people[i].name, people[i].age);
    }

    free(people);
    return 0;
}

Exercice 6 : Réallocation dynamique

Allouez un tableau de taille 5 avec calloc, puis redimensionnez-le pour contenir 10 éléments avec realloc. Affichez les valeurs avant et après la réallocation.

Solution :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array = (int *)calloc(5, sizeof(int));
    if (array == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    printf("Avant réallocation : ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    // Réallocation
    array = (int *)realloc(array, 10 * sizeof(int));
    if (array == NULL) {
        printf("Échec de la réallocation.\n");
        return 1;
    }

    printf("Après réallocation : ");
    for (int i = 0; i < 10; i++) {
        printf("%d ", array[i]); // Les nouveaux éléments ne sont pas initialisés à 0
    }
    printf("\n");

    free(array);
    return 0;
}

Résumé

malloccalloc
Alloue la mémoire mais ne l’initialise pas.Alloue la mémoire et l’initialise à zéro.
Peut être plus rapide pour des allocations simples.Plus sûr pour éviter les erreurs liées à des données non initialisées.
Nécessite une initialisation manuelle si nécessaire.Prêt à l’emploi avec des valeurs nulles ou zéro.

Guide : calloc vs malloc – Exercices Corrigés

Ce guide explique les différences entre calloc et malloc à travers des exercices pratiques corrigés. Vous apprendrez à choisir la fonction appropriée en fonction des besoins spécifiques.


1. Rappel des bases

malloc

  • Alloue un bloc de mémoire d’une taille totale spécifiée.
  • Ne l’initialise pas (valeurs indéterminées).
  • Syntaxe :
  void *malloc(size_t size);

calloc

  • Alloue de la mémoire pour un certain nombre d’éléments.
  • Initialise la mémoire allouée à zéro.
  • Syntaxe :
  void *calloc(size_t nitems, size_t size);

2. Exercices corrigés

Exercice 1 : Initialiser un tableau avec malloc

Allouez un tableau de 5 entiers avec malloc, puis initialisez-le à zéro.

Solution :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array = (int *)malloc(5 * sizeof(int));
    if (array == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Initialisation manuelle
    for (int i = 0; i < 5; i++) {
        array[i] = 0;
    }

    // Affichage
    for (int i = 0; i < 5; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    free(array);
    return 0;
}

Exercice 2 : Allouer un tableau avec calloc

Réalisez la même tâche que dans l’exercice précédent, mais utilisez calloc pour simplifier le code.

Solution :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array = (int *)calloc(5, sizeof(int));
    if (array == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Affichage : Pas besoin d'initialisation explicite
    for (int i = 0; i < 5; i++) {
        printf("%d ", array[i]); // Tous les éléments sont déjà 0
    }
    printf("\n");

    free(array);
    return 0;
}

Exercice 3 : Comparer les valeurs initiales de malloc et calloc

Allouez deux tableaux de taille 5, un avec malloc et l’autre avec calloc. Affichez leurs valeurs initiales.

Solution :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array_malloc = (int *)malloc(5 * sizeof(int));
    int *array_calloc = (int *)calloc(5, sizeof(int));

    if (array_malloc == NULL || array_calloc == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    printf("Valeurs avec malloc : ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", array_malloc[i]); // Valeurs indéterminées
    }
    printf("\n");

    printf("Valeurs avec calloc : ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", array_calloc[i]); // Toutes les valeurs sont 0
    }
    printf("\n");

    free(array_malloc);
    free(array_calloc);
    return 0;
}

Exercice 4 : Matrice avec malloc et calloc

Créez une matrice 3×3 (tableau 2D) avec :

  1. malloc : initialisez les valeurs à zéro manuellement.
  2. calloc : laissez calloc initialiser la mémoire.

Solution avec malloc :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int rows = 3, cols = 3;
    int *matrix = (int *)malloc(rows * cols * sizeof(int));
    if (matrix == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Initialisation manuelle
    for (int i = 0; i < rows * cols; i++) {
        matrix[i] = 0;
    }

    // Affichage
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i * cols + j]);
        }
        printf("\n");
    }

    free(matrix);
    return 0;
}

Solution avec calloc :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int rows = 3, cols = 3;
    int *matrix = (int *)calloc(rows * cols, sizeof(int));
    if (matrix == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Pas besoin d'initialisation : la mémoire est déjà zéro
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i * cols + j]);
        }
        printf("\n");
    }

    free(matrix);
    return 0;
}

Exercice 5 : Structures avec calloc

Déclarez une structure pour représenter une personne (nom, âge). Allouez un tableau de 3 personnes avec calloc et initialisez leurs valeurs par défaut.

Solution :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char name[50];
    int age;
} Person;

int main() {
    int n = 3;
    Person *people = (Person *)calloc(n, sizeof(Person));
    if (people == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    // Pas besoin d'initialiser explicitement : tous les champs sont déjà zéro
    for (int i = 0; i < n; i++) {
        printf("Personne %d : Nom = '%s', Âge = %d\n", i + 1, people[i].name, people[i].age);
    }

    free(people);
    return 0;
}

Exercice 6 : Réallocation dynamique

Allouez un tableau de taille 5 avec calloc, puis redimensionnez-le pour contenir 10 éléments avec realloc. Affichez les valeurs avant et après la réallocation.

Solution :

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array = (int *)calloc(5, sizeof(int));
    if (array == NULL) {
        printf("Échec de l'allocation.\n");
        return 1;
    }

    printf("Avant réallocation : ");
    for (int i = 0; i < 5; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");

    // Réallocation
    array = (int *)realloc(array, 10 * sizeof(int));
    if (array == NULL) {
        printf("Échec de la réallocation.\n");
        return 1;
    }

    printf("Après réallocation : ");
    for (int i = 0; i < 10; i++) {
        printf("%d ", array[i]); // Les nouveaux éléments ne sont pas initialisés à 0
    }
    printf("\n");

    free(array);
    return 0;
}

Résumé

malloccalloc
Alloue la mémoire mais ne l’initialise pas.Alloue la mémoire et l’initialise à zéro.
Peut être plus rapide pour des allocations simples.Plus sûr pour éviter les erreurs liées à des données non initialisées.
Nécessite une initialisation manuelle si nécessaire.Prêt à l’emploi avec des valeurs nulles ou zéro.

Recommandés

Guide complet : strcpy en C
La fonction strcpy en C est...
En savoir plus
Comment fonctionne la récursion terminale en C...
La récursion terminale en C La récursion...
En savoir plus
Exemple de QCM - Programmation en C
La programmation en C est une...
En savoir plus
Structure d'un Programme en Langage C
Le langage de programmation C, développé...
En savoir plus
Exploration complète du Tri par Fusion en...
Dans cet article, nous explorerons en...
En savoir plus
Les Majuscules en C: Une Porte vers...
Introduction Pour les débutants en programmation, comprendre...
En savoir plus
AZ

Recent Posts

Modèle Excel de plan de classification des documents administratifs

Les rouages d’une entreprise se jouent rarement sous les projecteurs. Ce qui apparaît à l’extérieur…

13 heures ago

Pages de garde de mémoire utilisées dans les universités françaises

Quand on prépare un mémoire, on consacre souvent l’essentiel de son énergie au plan, à…

15 heures ago

Modèle Excel d’analyse financière automatisée avec graphiques

Dans beaucoup d’entreprises, l’analyse financière commence souvent de la même manière : une pile de…

18 heures ago

Méthodologie SVT : réussir l’analyse de document en SVT

Télécharger une fiche méthode pratique et utile ⬇️ L’analyse de document en SVT fait partie…

23 heures ago

Méthode des points de vue narratifs en 4ème

Introduction En classe de 4ème, l’étude du récit occupe une place importante dans l’apprentissage du…

2 jours ago

Classification des Documents : Organiser et Automatiser la Gestion Documentaire

Télécharger un Modèle Excel de classification des documents avec suivi automatisé ⬇️ Dans toute organisation…

4 jours ago

This website uses cookies.