What is the difference between “calloc()” and “malloc()” in C/C++?

1 Answers
Answered by suresh

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

In C/C++, the primary difference between "calloc()" and "malloc()" is how they allocate memory. The focus keyword "calloc()" is used to allocate memory for an array of elements and initializes the allocated memory with zero, while "malloc()" is used to allocate a single block of memory without initializing it.

When using "calloc()", the syntax is:
void* calloc(size_t num, size_t size);

When using "malloc()", the syntax is:
void* malloc(size_t size);

It is important to note that while "calloc()" automatically initializes the allocated memory with zero values, "malloc()" does not perform any such initialization. Additionally, "malloc()" and "calloc()" both return a pointer to the allocated memory block or NULL if the allocation fails.

In summary, when you need to allocate memory for an array of elements and want the memory to be initialized with zeros, you should use "calloc()". For allocating a single block of memory without initialization, "malloc()" is the appropriate choice.

Answer for Question: What is the difference between “calloc()” and “malloc()” in C/C++?