calloc in C Programming

calloc()

The calloc function is used to allocate storage to a variable while the program is running. This library function is invoked by writing calloc(num,size).This function takes two arguments that specify the number of elements to be reserved, and the size of each element in bytes and it allocates memory block equivalent to num * size . The function returns a pointer to the beginning of the allocated storage area in memory. The important difference between malloc and calloc function is that calloc initializes all bytes in the allocation block to zero and the allocated memory may/may not be contiguous.

calloc function is used to reserve space for dynamic arrays. Has the following form.

void * calloc (size_t n, size_t size); 

Number of elements in the first argument specifies the size in bytes of one element to the second argument. A successful partitioning, that address is returned, NULL is returned on failure.

For example, an int array of 10 elements can be allocated as follows.

int * array = (int *) calloc (10, sizeof (int));

Note that this function can also malloc, written as follows.

int * array = (int *) malloc (sizeof (int) * 10); 

However, the malloc function, whereas the area reserved to the states that are undefined, the area allocated by the calloc function contains a 0. In fact, the calloc function is internally may be a function that calls malloc. After securing function by malloc, the area is filled with 0.

ptr = malloc(10 * sizeof(int)); 
//is just like this: 
ptr = calloc(10, sizeof(int));

The following example illustrates the use of calloc() function.

When you release the space allocated by calloc function, use the free function of course.

Ready to get started?

Ready to embark on your journey into the world of C programming? Our comprehensive course provides the perfect starting point for learners of all levels. With engaging lessons, hands-on exercises, and expert guidance, you'll gain the skills and confidence needed to excel in this fundamental programming language. Let's dive in and unlock the endless possibilities of C programming together!