Site icon Study Algorithms

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

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:-

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.

Exit mobile version