OverIQ.com

The calloc() Function in C

Last updated on July 27, 2020


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().

1
2
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:

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

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

1
2
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<stdio.h>
#include<stdlib.h>

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

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

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

    if(p==NULL)
    {
        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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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:

1
2
3
4
5
6
7
Enter the size of the array: 2
Enter 0 element: 11
Enter 1 element: 34

printing array of 2 integers

11 34