The calloc() Function in C

C provides another function to dynamically allocate memory which sometimes better than the malloc() function. Its syntax is:

Syntax: void *calloc(size_t n, size_t size);

It accepts two arguments the first argument is the number of the element, and the second argument is the size of elements. Let's say we want to allocate memory for 5 integers, in this case, 5 is the number of elements i.e n and the size of each element is 4 bytes (may vary from system to system). Here is how you can allocate memory for 5 integers using calloc().

int *p;
p = (int*)calloc(5, 4);

This allocates 20 bytes of contiguous memory space from the heap and assigns the address of first allocated byte to pointer variable p.

Here is how you can achieve the same thing using malloc() function:

int *p;
p = (int*)malloc(5 * 4);

To make our program portable and more readable sizeof() operator is used in conjunction with calloc().

int *p;
p = (int*)calloc(5, sizeof(int));

So apart from the number of arguments is there any other difference between calloc() and malloc() ?

The difference between calloc() and malloc() function is that memory allocated by malloc() contains garbage value while memory allocated by calloc() is always initialized to 0.

The following program uses calloc() to create dynamic (it can vary in size at runtime) 1-D array.


int main()
    int *p, i, n;

    printf("Enter the size of the array: ");
    scanf("%d", &n);

    p = (int*)calloc(n, sizeof(int));

        printf("Memory allocation failed");
        exit(1); // exit the program

    for(i = 0; i < n; i++)
        printf("Enter %d element: ", i);
        scanf("%d", p+i);
    printf("\nprinting array of %d integers\n\n", n);

    // calculate sum

    for(i = 0; i < n; i++)
        printf("%d ", *(p+i));
    // signal to operating system program ran fine
    return 0;

Expected Output:

1st run:

Enter the size of the array: 5
Enter 0 element: 13
Enter 1 element: 24
Enter 2 element: 45
Enter 3 element: 67
Enter 4 element: 89

printing array of 5 integers

13 24 45 67 89

2nd run:

Enter the size of the array: 2
Enter 0 element: 11
Enter 1 element: 34

printing array of 2 integers

11 34