Tuesday 12 June 2018

c - preferring malloc over 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?


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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...