What are the differences between malloc and calloc ?

28 Dec 2022 Balmiki Mandal 0 C Programming

What are the differences between malloc and calloc in C programming language?

malloc and calloc are both functions used to dynamically allocate memory in C. However, they differ in their behavior in the following ways:

  1. Syntax: The syntax for malloc and calloc is slightly different. malloc takes a single argument, which is the number of bytes to allocate, whereas calloc takes two arguments: the number of elements to allocate and the size of each element in bytes.

  2. Memory initialization: malloc allocates memory but does not initialize it. The memory block returned by malloc contains garbage values. On the other hand, calloc not only allocates memory but also initializes it to zero.

  3. Error handling: Both functions return a pointer to the allocated memory block if successful. However, if the memory allocation fails, malloc returns a NULL pointer, whereas calloc sets all the bytes of the allocated memory to zero and then returns a NULL pointer.

  4. Efficiency: calloc is slightly slower than malloc because it initializes the allocated memory block to zero. If the initialized memory is not required, malloc is a better choice as it is faster.

In summary, the main differences between malloc and calloc are in their syntax, memory initialization, error handling, and efficiency. It is important to choose the right function based on the specific needs of your program.

 

other habnd There are two basic differences.

First:

  • malloc() takes a single argument(memory required in bytes),
  • calloc() needs 2 arguments(number of variables to allocate memory, size in bytes of a single variable).

Second 

  • malloc() does not initialize the memory allocated,
  • calloc() initializes the allocated memory to ZERO

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.