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

12

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

    
asked by anonymous 23.01.2017 / 11:35

1 answer

15

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

Zerar means to place byte 0 in all allocated memory locations.

It is probably little used, by those who understand it, because it is a bit slower than malloc() and in well-written codes it is likely that soon there will be some useful value in that space, the zeroing would be a waste. It should also have case where it is what one wants and the programmer is unaware of the functionality. Some people do not use it because they do not know.

Remember that in C if you allocate memory and access immediately it will pick up garbage, that is, values that were there in memory previously. This can be problematic. Or it may be what you want, so C leaves it open. High-level languages always clear memory, runtime often does it intelligently to avoid double-working, but it does not always make it the most optimized form. I've already seen language that 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 tends to be faster than doing separate in various situations.

    
23.01.2017 / 11:35