calloc and malloc functions in c

Example to illustrate malloc:

void * calloc(int nelements, int bytes);

  • Allocates a region of memory large enough to hold nelements of size bytes each.
  • The allocated region is initialized to zero. In the above example:

Eg: int *ptr = (int *) calloc(10, sizeof(int));

Difference between malloc and calloc:
1. malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.
2. Zeroing out the memory may take a little time, so you malloc is faster than calloc. Use calloc if initializing the memory is important.

calloc(m, n) is the same as
p = malloc(m * n);
if(p) memset(p, 0, m * n);

3. A less known difference is that in operating systems with optimistic memory allocation, like Linux, the pointer returned by malloc isn’t backed by real memory until the program actually touches it.



Mr. Sandeep Soni

Founder, Trainer & CEO, Deccansoft Software Services.

Sandeep has 21 yrs of experience working in various Microsoft Technologies/Platforms incl. VB6.0, ASP, VC++, VB.NET, C#. He is involved in managing and architecting projects at Deccansoft. He will be your liaison to Deccansoft, for any kind of communication and project updates. He knows what works and what doesn’t, and what practices are most suitable for design and programming with the ultimate goal of producing a quality system.