What is the advantage of zeroing out memory (i.e. calloc()
over malloc()
)? Won't you change the value to something else anyways?
calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you try to read the value of the allocated memory without initializing it, you'll get 0 as it has already been initialized to 0 by calloc().
calloc does not necessarily have to initialize the memory to zero by itself. The description of calloc says that: Show activity on this post. In short, it's more portable to set the memory to zero explicitly if that's what your application needs; and faster to leave it alone if it doesn't.
calloc will initialize the memory to zero. So, the allocated memory area will be set to 0.
Memory that's initialized to zero is memory in which every addressable object (every byte), will always have a value equal to zero, when you read it as an non-padded type (e.g. unsigned char ), It's useful in the sense that you always get the same memory contents (instead of "random" garbage).
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 :-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With