What is the advantage of zeroing out memory (i.e. calloc()
over malloc()
)? Won't you change the value to something else anyways?
There are two camps: one says that initializing variables when they are declared helps find bugs. The people in this camp make sure everything they declare is initialized. They initialize pointers to NULL
, int
s to 0, etc. The idea is that everything is determinate, and when they see a NULL
-pointer in a debugger, they immediately know it wasn't set properly. It can also help your program crash during testing because of NULL
-pointer dereferencing rather than mysteriously crashing in production runs.
The other camp says that initializing variables at declaration makes things harder to debug, because now a compiler can't warn you about variables "used without being set".
Without telling you my personal preference1: if you belong to the first camp, you would want to calloc()
instead of malloc()
. If you belong to the second camp (which apparently you do) then you prefer malloc()
over calloc()
.
Now there are two exceptions:
calloc()
but malloc()
because you are initializing floating-point numbers or pointers, and you know that all bits zero doesn't necessarily mean 0
for them. Or, you don't want the extra overhead.calloc()
when you are allocating some data and want it to be all zeroes. For example, if you want to calculate the row-wise sum of an n
by m
dynamically allocated int
data.1 You can see my answers to many of the questions here on SO to see which camp I belong to :-).