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

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

a) calloc() initializes the allocated memory to zero, malloc() does not
b) malloc() initializes the allocated memory to zero, calloc() does not
c) malloc() and calloc() allocate memory on different memory segments
d) calloc() can allocate memory for more than one data type, malloc() cannot

Answer:

a) calloc() initializes the allocated memory to zero, malloc() does not

Explanation:

Both malloc() and calloc() are used to allocate memory dynamically in C. However, there is a key difference: malloc() allocates a block of memory of a specified size without initializing it, meaning the memory contains garbage values. In contrast, calloc() allocates memory for an array of elements, initializes all bytes in the allocated memory to zero, and then returns a pointer to the allocated memory. This makes calloc() useful when you need to ensure that the memory is zeroed out before use.

Understanding the difference between malloc() and calloc() helps in choosing the right function based on whether memory initialization is required.

Reference links:

https://www.rameshfadatare.com/learn-c-programming/

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top