What is the difference between malloc()
and calloc()
in C?
a)
calloc()
initializes the allocated memory to zero, malloc()
does notb)
malloc()
initializes the allocated memory to zero, calloc()
does notc)
malloc()
and calloc()
allocate memory on different memory segmentsd)
calloc()
can allocate memory for more than one data type, malloc()
cannotAnswer:
a)
calloc()
initializes the allocated memory to zero, malloc()
does notExplanation:
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.