Differences between calloc and malloc functions

What is the difference between the malloc function and calloc? Are there any cases where only one of these functions is suitable?

Author: Андрей, 2017-04-06

2 answers

First, the calloc function, unlike malloc, returns a pointer to the initialized block of memory, i.e., initially containing zero bits1. This, however, does not mean that the function calloc itself is engaged in zeroing the received memory block in the context of the user process. The calloc function can take advantage of the more efficient zeroing facilities provided by the underlying platform, i.e., for example, allocate memory in the pool of" zeroed pages " of the OS or use a certain mechanism of "lazy" zeroing of the hardware/OS level. That is, if you need a zeroed block of memory, then in general, getting such a block of memory through calloc can be a significantly more efficient operation than "manually" zeroing a block of memory obtained through malloc.

Secondly, the function calloc, as it is easy to see, internally calculates the total size of the requested memory block (literally, multiplying its arguments). In this case, the calloc function must independently track the correctness of such multiplication, i.e. detect an error when an overflow occurs. In the case of using the malloc function, such multiplication (if necessary) is performed by the calling code, and preventing overflow is the responsibility of the calling code.


1 From the language point of view, this does not guarantee the correct formation of null pointers and null values of the floating type.

 16
Author: AnT, 2017-05-23 12:39:08

malloc simply allocates the memory, leaving its contents undefined, and calloc is guaranteed to reset it. Which is not always necessary, but it takes time...

 6
Author: Harry, 2017-04-06 14:24:42