Can anyone explain what is the difference between using malloc() and calloc() for dynamic memory allocation in C?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With