Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Between malloc and calloc which allocates contiguous memory

Tags:

c

malloc

calloc

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.

like image 997
bvb Avatar asked Dec 07 '22 03:12

bvb


2 Answers

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.

like image 177
unwind Avatar answered Dec 08 '22 18:12

unwind


They both return contiguous memory:

7.22.3.4

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

7.22.3.2

The calloc function allocates space for an array of nmemb objects, each of whose size is size. The space is initialized to all bits zero.

6.2.6.1.2

Except for bit-fields, objects are composed of contiguous sequences of one or more bytes, the number, order, and encoding of which are either explicitly specified or implementation-defined.

and 6.2.5.20

An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type

like image 43
msam Avatar answered Dec 08 '22 17:12

msam