I have just learned about the C calloc()
function the other day. Having read its description and how it differs from malloc
(1, 2), I get the idea that, as a non-embedded programmer, I should always use calloc()
. But is that really the case?
One reservation I have is the extra delay for accessing the calloc()
-ed memory, but I also wonder if there are cases when switching from malloc()
to calloc()
will break the program in some more serious way.
P. S. The zero-initializing aspect of calloc()
is quite clear to me. What I'm interested in learning about is the other difference between calloc()
and malloc()
- lazy memory allocation provided by calloc()
. Please don't post an answer if you're going to focus purely on the memory initialization aspect.
The main difference between
malloc
andcalloc
is thatcalloc
will zero-initialize your buffer, andmalloc
will leave the memory uninitialized.This gets to the common programming idiom of "don't pay for what you don't use". In other words, why zero-initialize something (which has a cost) if you don't necessarily need to (yet)?
As a side note since you tagged C++: manual memory usage using
new/delete
is frowned upon in modern C++ (except in rare cases of memory pools, etc). Use ofmalloc/free
is even more rare and should be used very sparingly.