calloc allocates num blocks of memory, each of size size:
void * calloc ( size_t num, size_t size );Allocate space for array in memory
Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.
In contrast, malloc allocates one block of memory of size size:
void * malloc ( size_t size );Allocate memory block
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
Is there any difference between both (except for the zero-initialization by calloc)?
What does calloc means exactly by num blocks of memory as in practice the returned memory region is contiguous as well.
I believe there has to be some difference, otherwise it wouldn’t make much sense to define two different interfaces for these methods?
In practice they do the same thing. The advantage of calloc is that good implementations will perform an overflow detection when doing the multiplication needed to determine how much memory you need.
If you do it something like this:
‘sz’ might not end up being what you expect it to be. malloc will then allocate much less than the caller expected, but the caller can end up treating the returned area as large enough. This leads to heap overflows will all the security implications that usually has.