4

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.

Community
  • 1
  • 1
Addtoc
  • 45
  • 3

2 Answers2

9

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • HI John, So,malloc(s) returns a pointer with enough storage with s bytes, where as calloc(n,s) returns a pointer with enough contiguous storage each with s bytes....so here calloc is returning n contiguous block of s bytes while malloc is returning a single block of s byte... Correct me if I am wrong. – Addtoc Oct 17 '12 at 19:05
1

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.

Yefim Dinitz
  • 414
  • 3
  • 9