Langage C/C++

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.

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.

Autres articles

Pointeurs en C - Exercices Corrigés avec...
Ce guide propose des exercices corrigés sur les pointeurs en...
Read more
La Vérité sur les Tableaux et les...
Les tableaux et les pointeurs sont au cœur du langage...
Read more
Guide : Déclarer un Pointeur en C...
Cet article vous montre comment déclarer un pointeur en C...
Read more
Guide : L'Allocation Dynamique en C
L'allocation dynamique en C permet de gérer la mémoire de...
Read more
Quand Utiliser les Pointeurs en C ?
Les pointeurs en C sont une fonctionnalité puissante qui permet...
Read more
Guide Complet : Pointeur de Pointeur en...
Un pointeur de pointeur (ou double pointeur) en C est...
Read more
AZ

Recent Posts

Correspondance Professionnelle : Méthodes de Rédaction et Types

La correspondance professionnelle est essentielle dans le monde du travail. Elle englobe divers types de…

9 heures ago

Lettre de Motivation Type : Modèle et Conseils de Rédaction ( Canevas Word à Télécharger)

La lettre de motivation est un document clé pour postuler à un emploi, un stage…

10 heures ago

📌 Analyse de Texte : Exercices Corrigés et Fiche Méthode

L’analyse de texte est une compétence essentielle en communication, en littérature et en sciences humaines.…

11 heures ago

📌 Exercices Corrigés de Communication Professionnelle +Fiche Méthode

La communication professionnelle est un levier essentiel en entreprise et dans l’administration. Elle permet de…

12 heures ago

Courrier Administratif : Exemplaire, Structure et Formalités

Le courrier administratif est un outil de communication essentiel dans les échanges entre particuliers, entreprises…

12 heures ago

Exemplaire de courrier officiel : Présentation, Structure et Formalités

Dans la communication professionnelle et administrative, la rédaction d’un courrier officiel est une compétence essentielle.…

13 heures ago

This website uses cookies.