What is the difference between" calloc () "and"malloc ()"?

What does the function calloc() do that malloc() does not? Why is it almost not used?

Author: Maniero, 2017-01-23

1 answers

calloc() does the same thing as malloc(), allocates memory in the heap according to the size passed and returns a pointer to the place where there was the allocation, with an extra, it zeros out all allocated space.

Zeroing means putting byte 0 in all allocated memory positions.

It is probably little used, by those who understand, because it is a little slower than malloc() and in well-written codes it is likely that soon after it will be placed some useful value in that space, then it would be double work and zeroing would be a waste. It should also have case where it is what is desired and the programmer is unaware of the functionality so it does not use.

Remember that in C if you allocate memory and access it will immediately pick up garbage, that is, values that were there in memory previously. This can be problematic. Or it can be what you want, so the language leaves open. Higher-level languages always zero memory, many times the runtime does it intelligently to avoid double work, but it can't always do it in the most optimal way. I've seen language that zeroes by default and lets it shut down in an exceptional case.

calloc() it's like calling malloc() and memset() next. But note that calloc() is "smart" and in various situations tends to be faster than doing separate.

 23
Author: Maniero, 2020-04-15 16:29:41