Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between malloc() and calloc()?

Can anyone explain what is the difference between using malloc() and calloc() for dynamic memory allocation in C?

like image 957
Kusum Adhikari Avatar asked Sep 26 '26 21:09

Kusum Adhikari


1 Answers

Try doing this: Allocate some memory using malloc like

char* pszKuchBhi ;
pszKuchBhi = malloc(10) ;
printf( "%s\n", pszKuchBhi ) ;  
// Will give some junk values as the memory allocated is not initialized and 
// was storing some garbage values

Now do the same while replacing malloc with calloc. See the difference.

char* pszKuchBhi ;
pszKuchBhi = calloc( 10, 1 ) ;
printf( "%s\n", pszKuchBhi ) ; 
//Will print nothing as the memory is initialized to 0

The memory assigned by calloc is initialized to 0. Its good for beginners to initialize the memory but performance-wise calloc is slow as it has to allocate and then initialize. For better clarification, you can always google the same question but better to experience it to have a look inside. You can also keep a watch on your memory to see it for yourself.

like image 72
Abhineet Avatar answered Sep 30 '26 01:09

Abhineet