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

Asked

Viewed 9,539 times

23

What the function calloc() makes the malloc() Doesn’t it? Why is it hardly used?

1 answer

26


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

Zerar means to put byte 0 in all allocated memory positions.

It is probably little used, by those who understand, because it is a little slower than the malloc() and in well-written codes it is likely that soon afterwards some useful value will be placed in that space, so it would be double work and zero would be a waste. There must also be case where is what is desired and the programmer does not know the functionality so do not use.

Remember that in C you allocate memory and immediately access junk, that is, values that were there in memory earlier. This can be problematic. Or it can be what you want, so the language leaves it open. Higher-level languages always reset memory, often the Runtime does it intelligently to avoid double work, but it does not always manage to do it in the most optimized way. I’ve seen language that Zera by default and lets turn it off in an exceptional case.

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

  • 1

    Actually, reading from an uninitialized storage has undefined behavior. That is, anything can happen other than just reading "junk".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.