Home Misc What is the difference between calloc() and malloc() ?

What is the difference between calloc() and malloc() ?

by nikoo28
0 comment 2 minutes read

Question:

What is the difference between doing:
        ptr = (char **) malloc (MAXELEMS * sizeof(char *));
or:
        ptr = (char **) calloc (MAXELEMS, sizeof(char*));

When is it a good idea to use calloc and when to use malloc ?

There are two differences:-

  • Firstly it is in the number of arguments, malloc() takes a single argument (memory required in bytes), while calloc() needs two arguments.
  • Secondly, malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.

calloc() allocates a memory area, the length will be the product of its parameters. calloc fills the memory with ZERO’s and returns a pointer to first byte. If it fails to locate enough space it returns a NULL pointer.

Syntax: ptr_var=(cast_type *)calloc(no_of_blocks , size_of_each_block);

//below is a sample line
ptr_var = (type *)calloc(n,s);

malloc() allocates a single block of memory of REQUSTED SIZE and returns a pointer to first byte. If it fails to locate requsted amount of memory it returns a null pointer.

Syntax:ptr_var=(cast_type *)malloc(Size_in_bytes);

//below is a sample line
ptr_var = (type *)malloc(n*s);

In a brief summary calloc() zero-initializes the buffer, while malloc() leaves the memory uninitialized.

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More