calloc
is initializing the memory before you use it, but malloc
does not.
Refer to this link:
The calloc() function shall allocate
unused space for an array of nelem
elements each of whose size in bytes
is elsize. The space shall be
initialized to all bits 0.
With malloc
, if you want to guarantee the same effect you'd have to call something like memset to reset the memory, e.g.
char* buffer = (char*)malloc(100);
memset(buffer,0,100);
calloc
saves you that extra step.
The significance of initializing memory is that you are getting a variable to a known state rather than an unknown one. So if you are checking a variable, say an array element, for an expected value, then by having pre-initialized the variable ahead of time, you can be sure that the value you are checking isn't garbage. In other words, you can distinguish between garbage and legitimate values.
For example, if you just leave garbage in the variable and you are checking for some value, say 42, then you have no way of knowing if the value was really set to 42 by your program, or if that's just some garbage leftover because you didn't initialize it.