Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preferring malloc over calloc [duplicate]

Tags:

c

malloc

calloc

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?

like image 868
user514946 Avatar asked Nov 22 '10 05:11

user514946


2 Answers

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.

like image 92
James McNellis Avatar answered Sep 26 '22 02:09

James McNellis


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.

like image 43
asdfjklqwer Avatar answered Sep 25 '22 02:09

asdfjklqwer