C - calloc() - Memory Allocation with the calloc() Function


The calloc() function declared in the stdlib.h header offers a couple of advantages over malloc().

First, it allocates memory as a number of elements of a given size.

Second, it initializes the memory allocated to zero.

The calloc() function requires two argument values:

  • the number of data items for which space is required and
  • the size of each data item.

Both arguments are expected to be of type size_t.

Here's how you could use calloc() to allocate memory for an array of 75 elements of type int:

int *pNumber = (int*) calloc(75, sizeof(int));

The return value will be NULL if it was not possible to allocate the memory requested.

pPrimes = calloc((size_t)total, sizeof(unsigned long long));
if (primes == NULL)
   printf("Not enough memory. It's the end I'm afraid.\n");
   return 1;