Last updated on July 27, 2020
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 for5 integers, in this case,5 is the number of elements i.en and the size of each element is4 bytes (may vary from system to system). Here is how you can allocate memory for 5 integers usingcalloc().
12 | int*p;p=(int*)calloc(5,4); |
This allocates20 bytes of contiguous memory space from the heap and assigns the address of first allocated byte to pointer variablep.
Here is how you can achieve the same thing usingmalloc() function:
12 | int*p;p=(int*)malloc(5*4); |
To make our program portable and more readablesizeof() operator is used in conjunction withcalloc().
12 | int*p;p=(int*)calloc(5,sizeof(int)); |
So apart from the number of arguments is there any other difference betweencalloc() andmalloc()?
The difference betweencalloc() andmalloc() function is that memory allocated bymalloc() contains garbage value while memory allocated bycalloc() is always initialized to0.
The following program usescalloc() to create dynamic (it can vary in size at runtime) 1-D array.
1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334 | #include<stdio.h>#include<stdlib.h>intmain(){int*p,i,n;printf("Enter the size of the array: ");scanf("%d",&n);p=(int*)calloc(n,sizeof(int));if(p==NULL){printf("Memory allocation failed");exit(1);// exit the program}for(i=0;i<n;i++){printf("Enter %d element: ",i);scanf("%d",p+i);}printf("\nprinting array of %d integers\n\n",n);// calculate sumfor(i=0;i<n;i++){printf("%d ",*(p+i));}// signal to operating system program ran finereturn0;} |
Expected Output: 1st run:
1 2 3 4 5 6 7 8 910 | Enter the size of the array: 5Enter 0 element: 13Enter 1 element: 24Enter 2 element: 45Enter 3 element: 67Enter 4 element: 89printing array of 5 integers13 24 45 67 89 |
2nd run:
1234567 | Enter the size of the array: 2Enter 0 element: 11Enter 1 element: 34printing array of 2 integers11 34 |