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?
Answer
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.
No comments:
Post a Comment