Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in block allocated by malloc/calloc [duplicate]

Tags:

c

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.

like image 453
Addtoc Avatar asked Dec 27 '22 15:12

Addtoc


2 Answers

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.

like image 83
John Kugelman Avatar answered Feb 11 '23 21:02

John Kugelman


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 calloced memory will be set to zero, while malloc returns a pointer to uninitialized memory.

like image 29
Yefim Dinitz Avatar answered Feb 11 '23 19:02

Yefim Dinitz