preferring malloc over 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?
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 for char types as expected. But it doesn't necessarily correspond to float/double 0 or NULL pointers.
You're normally allocating memory with the specific intent of storing something there. That means (at least most of) the space that's zero-initialized by calloc
will soon be overwritten with other values. As such, most code uses malloc
for a bit of extra speed with no real loss.
Nearly the only use I've seen for calloc
was code that was (supposedly) benchmarking the speed of Java relative to C++. In the C++ version, it allocated some memory with calloc
, then used memset
to initialize the memory again in (what seemed to me) a fairly transparent attempt at producing results that favored Java.
上一篇: malloc和calloc
下一篇: 喜欢malloc over calloc