Possible Duplicate:
c difference between malloc and calloc
Is there any situation where you would prefer malloc over calloc. i know both malloc and calloc allocate memory dynamically and that calloc also initializes all bits in alloted memory to zero. From this i would guess its always better to use calloc over malloc. Or is there some situations where malloc is better? Performance may be?
If you need the dynamically allocated memory to be zero-initialized then use calloc
.
If you don't need the dynamically allocated memory to be zero-initialized, then use malloc
.
You don't always need zero-initialized memory; if you don't need the memory zero-initialized, don't pay the cost of initializing it. For example, if you allocate memory and then immediately copy data to fill the allocated memory, there's no reason whatsoever to perform zero-initialization.
calloc
and malloc
are functions that do different things: use whichever one is most appropriate for the task you need to accomplish.
Relying on calloc's zero-initialisation can be dangerous if you're not careful. Zeroing memory gives 0 for integral types and \0 for char types as expected. But it doesn't necessarily correspond to float/double 0 or NULL pointers.
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