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.

AZ

Recent Posts

Questionnaire d’Entretien d’Embauche pour Gestionnaire de Paie

Le gestionnaire de paie avance souvent dans l’ombre, pourtant son travail influence directement la confiance…

1 heure ago

Questionnaire d’entretien d’embauche pour technicien de maintenance industrielle

Dans l’industrie, certaines minutes coûtent extrêmement cher. Lorsqu’une machine stratégique s’arrête au milieu d’une production,…

3 jours ago

Calcul d’incertitude : Exercices corrigés

Le calcul d’incertitude constitue une étape essentielle dans toute mesure scientifique. En physique, en chimie,…

5 jours ago

QCM Fanuc : Quiz Formation fraisage Fanuc : entraînement programmation CNC

Le fraisage CNC sous commande Fanuc repose sur une logique de précision, de trajectoires coordonnées…

5 jours ago

Langage Fanuc en tournage CNC : guide complet de programmation ISO industrielle

Le langage Fanuc s’impose aujourd’hui comme l’un des fondements de l’usinage CNC moderne. Derrière les…

5 jours ago

Questions pièges en entretien d’embauche : méthodes et réponses pour réussir

Un entretien d’embauche ressemble rarement à une conversation ordinaire. Derrière des questions en apparence simples…

2 semaines ago

This website uses cookies.