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

Question:

What does the calloc() function do that malloc() does not? Or the other way around. And why is it hardly used? At least I don't see that much.

Answer:

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

Zeroing means putting byte 0 in all allocated memory locations.

It's probably underused, by those who understand, because it's a little slower than malloc() and in well-written code it's likely that some useful value will soon be put into this space, so it would be double work and zeroing would be a waste. There must also be a case where it is what you want and the programmer is not aware of the functionality and therefore does not use it.

Remember that in C, allocating memory and accessing immediately will get garbage, that is, values ​​that were there in memory before. This can be problematic. Or it can be what you want, so the language leaves it open. Higher level languages ​​always zero out memory, often the runtime does it smartly to avoid double work, but it doesn't always manage to do it optimally. I've seen language that resets by default and lets you turn it off in an exceptional case.

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

Scroll to Top