Difference between malloc and calloc in C

by | Aug 21, 2022 | C

The main difference between both functions is malloc never initializes the allocated memory with zero value whereas calloc function is the one that initializes the allocated memory with the zero value.

Let’s prove the statement written above with the help of programs.

Program with Calloc

#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
printf("Enter number of elements:");
scanf("%d",&n);


int *p;
p=(int*)calloc(n, sizeof(int));
if(p==NULL)
{
printf("\nMemory cannot be allocated\n");
}
else
{
printf("Elements of array are:\n");
for(int i=0;i<n;i++)
{
printf("%d\n",*(p+i));
}
}


return 0;
}

 

Output

In the above code, we use the calloc function, but we only specified the number of elements without initializing them. So, as a result, calloc initializes each of the elements of the array with 0, and thus, the value of all the eight elements is printed 0.

This proves that calloc function initializes the allocated memory with 0 value.

This time writing the same code as written above with malloc function.

Program with Malloc

#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
printf("Enter number of elements:");
scanf("%d",&n);


int *p;
p=(int*)malloc(n* sizeof(int));
if(p==NULL)
{
printf("\nMemory cannot be allocated\n");
}
else
{
printf("Elements of array are:\n");
for(int i=0;i<n;i++)
{
printf("%d\n",*(p+i));
}
}


return 0;
}

 

Output

Using the malloc function, we compiled the same code but didn’t get the same output. malloc function doesn’t initialize the elements to 0. Rather it assigns some garbage value to each element of the array.

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.