I am reading about pointers and dynamic memory allocation in C. I have found that the function calloc()
is similar to malloc()
but the former does initialize memory to 0.
I do not understand why does it mean to initialize memory to zero?
NOTE: I am not asking the difference between malloc and calloc, but the meaning of initializing memory to zero.
Thanks in advance.
p = calloc(12, 1024);
Is roughly equivalent to:
p = malloc(12 * 1024);
if (p != NULL)
memset(p, 0, 12 * 1024);
So calloc
does two things that malloc
does not:
nmemb
and size
variables to calculate the total size of the allocationFor this purpose, calloc
is good for allocating arrays, particular arrays of scalar values.
There are cases where this initialization is undesirable:
NULL
may not be all zeros.