malloc
and calloc
have these signatures:
void* malloc( size_t size );
void* calloc( size_t num, size_t size );
They do basically the same thing. Both allocate a chunk of memory of the specified size and return a pointer to that chunk. The difference is that calloc
initializes the whole memory to zeros. Actually, calloc
could be implemented kind of like this:
void* calloc( size_t num, size_t size ) {
void * ptr = malloc(num*size);
if(!ptr) return NULL;
return memset(ptr,0,num*size);
}
(I know that there are reasons to not implement it like this, but that's not the topic.)
Since they are so similar, what is the reason for their different signatures? When you call malloc
you specify the number of bytes you want and when you're calling calloc
you specify a block size and the number of blocks. I don't prefer one over the other, but it bothers me that they are different.
Imagine that you have written a piece of code with some malloc
s, and then you realize that all of these allocations need to be zeroed. If they had the same signature it would mean that you only have to change the "m" to a "c".
Was there ever a reason for this design choice, or was it just a coincidence?