Possible Duplicate:
c difference between malloc and calloc
Though calloc allocates memory in the form of blocks and malloc in a single block , do they both allocate memory continuously and if there is an obstacle , would calloc be able to jump the obstacle then allocate another block in remaining heap memory. I would like clarity in the matter.
Both functions allocate memory in one contiguous block. The difference in parameters does not reflect a difference in the underlying allocation strategy. It's a historical inconsistency, nothing more.
(You can reason your way to this conclusion. If calloc were to allocate non-contiguous blocks, how would the caller know where the holes are and how to skip over them? All the caller receives is a single pointer. Not, say, a linked list of blocks, which is what would be required to access non-contiguous regions.)
You either call calloc(n,s)
or malloc(n*s)
; calloc does the multiplication for you, that's all. You could switch the arguments to calloc(s,n)
if you wanted. The idea that it allocates "s" objects of size "n" is just a conceptual one, the system doesn't actually keep track of that or enforce it. calloc(4,1)
is equivalent to calloc(1,4)
is equivalent to calloc(2,2)
.
The only meaningful distinction between the two is that calloc sets the memory to zero. malloc leaves it uninitialized, so it is more efficient if you don't need the memory cleared.
As John says the difference exists for historical reasons and there is no actual difference in the allocation strategy. One difference worth pointing out, though, is that calloc
ed memory will be set to zero, while malloc
returns a pointer to uninitialized memory.
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