w3resource

Understanding the difference between malloc and calloc in C


Difference between malloc and calloc in C Language


In C, dynamic memory allocation allows programs to request memory at runtime, rather than at compile-time. The functions malloc and calloc are two standard library functions that allocate memory dynamically. While both are used for memory allocation, they differ in their initialization behavior and parameters.

malloc (Memory Allocation):

  • Purpose: Allocates a block of memory of specified size in bytes.
  • Initialization: Does not initialize the allocated memory; the memory block contains garbage values.
  • Syntax: void* malloc(size_t size);

Example:

int *arr = (int*) malloc(5 * sizeof(int)); // Allocates memory for 5 integers 

calloc (Contiguous Allocation):

  • Purpose: Allocates memory for an array of elements, initializing each element to zero.
  • Initialization: Initializes all bits of allocated memory to zero.
  • Syntax: void* calloc(size_t num, size_t size);

Example:

int *arr = (int*) calloc(5, sizeof(int)); // Allocates and initializes memory for 5 integers to zero

Key Differences

Parameters:

  • malloc takes a single parameter: the total number of bytes to allocate.
  • calloc takes two parameters: the number of elements and the size of each element.

Initialization:

  • malloc leaves memory uninitialized.
  • calloc initializes memory to zero.

Example: Comparing malloc and calloc

The following code demonstrates the difference in behaviour between malloc and calloc:

Code:

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

int main() {
    int *arr1, *arr2;
    int n = 7;

    // Using malloc
    arr1 = (int*) malloc(n * sizeof(int));
    printf("Memory allocated by malloc (contains garbage values):\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr1[i]); // May print garbage values
    }
    printf("\n");

    // Using calloc
    arr2 = (int*) calloc(n, sizeof(int));
    printf("Memory allocated by calloc (initialized to zero):\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr2[i]); // Should print 0
    }
    printf("\n");

    // Freeing memory
    free(arr1);
    free(arr2);

    return 0;
}

Output:

Memory allocated by malloc (contains garbage values):
11492848 0 11469136 0 1953384765 1701737061 2017796212
Memory allocated by calloc (initialized to zero):
0 0 0 0 0 0 0

Summary

  • malloc: Allocates memory but does not initialize it; often used when initialization is unnecessary.
  • calloc: Allocates memory and initializes all bytes to zero; useful when zero-initialized memory is required.


Follow us on Facebook and Twitter for latest update.