C library - calloc() function



The C stdlib library calloc() function is used to allocates the requested memory and returns a pointer to it. It reserves a block of memory for array of objects and initialize all bytes in the allocated storage to zero.

If we try to read the value of the allocated memory without initializing it, we will get 'zero' because it has already been initialized to 0 by calloc().

Syntax

Following is the C library syntax of the calloc() function −

void *calloc(size_t nitems, size_t size)

Parameters

This function accepts following parameters −

  • nitems − It represents the number of element to be allocated.

  • size − It represents the size of each element.

Return Value

following is the returns value −

  • Returns pointer to allocated memory with all bytes initialized to zero.

  • If the allocation fails, then it returns a null pointer.

Example 1

In this example, we create a basic c program to demonstrate how to use the calloc() function.

#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 5;
   int *array;
   
   // use calloc function to allocate the memory
   array = (int*)calloc(n, sizeof(int));
   
   if (array == NULL) {
      fprintf(stderr, "Memory allocation failed!\n");
      return 1;
   }
   
   //Display the array value
   printf("Array elements after calloc: ");
   for (int i = 0; i < n; i++) {
      printf("%d ", array[i]);
   }
   printf("\n");
   
   //free the allocated memory
   free(array);
   return 0;
}

Output

Following is the output −

Array elements after calloc: 0 0 0 0 0 

Example 2

Let's create another c example, we allocate memory to a number, using the calloc() function.

#include <stdio.h>
#include <stdlib.h>
int main() {	
   long *number;   
   //initialize number with null
   number = NULL;
   if( number != NULL ) {
      printf( "Allocated 10 long integers.\n" );
   }      
   else {
      printf( "Can't allocate memory.\n" );
   }
   
   //allocating memory of a number
   number = (long *)calloc( 10, sizeof( long ) );
   if( number != NULL ) {
      printf( "Allocated 10 long integers.\n" );
   }      
   else {
      printf( "\nCan't allocate memory.\n" );
   }   
   //free the allocated memory   
   free( number );
}

Output

Following is the output −

Can't allocate memory.
Allocated 10 long integers.

Example 3

Below is the c program to allocate memory to a pointer using the the calloc() function with zero size.

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

int main() {
   int *pointer = (int *)calloc(0, 0);
   if (pointer == NULL) {
      printf("Null pointer \n");
   } else {
      printf("Address = %p", (void*)pointer);
   }
   free(pointer);
   return 0;
}

Output

Following is the output −

Address = 0x55c5f4ae02a0
Advertisements