Differences between malloc() and calloc()?
c, dynamic-memory-allocation
Solution
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.
Problem
Can anyone explain what is the difference between using `malloc()` and `calloc()` for dynamic memory allocation in C?