The calloc function dynamically allocates memory from the application memory heap. The function returns an address to the allocated memory block, which can be stored in a pointer to the desired data type. Differently from the malloc function, calloc initilizes the returned data with zeros, so it presents a small additional overhead over malloc.

The calloc function requires two argument. The first argument is the number of data objects that must be allocated. The second argument specifies the size of the memory block that the application is trying to allocate.

The return value of the calloc function is "void *", an it requires a cast to a pointer of the required data type.

The following code shows an example of calloc in use:

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

int main()
        int i;
        int num_elements = 10;
        int *p;
        p = (int *)calloc(10, sizeof(int));
        for (i=0; i<num_elements; i++) {
                printf("%d ", p[i]);
                p[i] = i+1;
        for (i=0; i<num_elements; i++) {
                printf("%d ", p[i]);
        return 0;

The result of this code is the following:

0 0 0 0 0 0 0 0 0 0
1 2 3 4 5 6 7 8 9 10
Article created on 2008-08-19 21:46:31

Post a comment