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

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:

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

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.

Expected Output:

1st run:

2nd run:

Leave a Comment

%d bloggers like this: