I read so many links regarding malloc and calloc but still Iam bit confused about "Between malloc and calloc which allocates contiguous memory".
In some links they have given malloc allocates contiguous memory as a block of bytes But in some links they have given calloc allocates contiguous memory for an array of elements.
Please give me clear idea about that.
Both calls allocate continuous memory.
Basically, calloc()
can be thought of as being a (thin) wrapper on top of malloc()
:
void * calloc(size_t nmemb, size_t size)
{
const size_t bytes = nmemb * size;
void *p = malloc(bytes);
if(p != NULL)
memset(p, 0, bytes);
return p;
}
The point is that it doesn't have any particular magic role, it's just allocating memory just like malloc()
, but happens to a) initialize it, and b) have an interface which makes it easy to use when you're going to use the returned pointer as an array.
Note that, as usual on modern computers with virtual memory, there is no guarantee that the underlying (physical) memory is continuous, of course. But since all access will be through virtual addresses mapped by the operating system, that doesn't matter.