3 ms·
Does anyone know if this is actually true? By that, I mean the title of this article, 'Why does calloc exist?'. My guess would be that back in the origins of t
by joosters 4y ago
Does anyone know if this is actually true?
By that, I mean the title of this article, 'Why does calloc exist?'. My guess would be that back in the origins of the C library:
1) Few cared about automatic overflow checks, that was a job for the programmer, so it seems unlikely the creators added calloc() specifically so that it could check if m * n overflowed (after all, there are loads of libc calls that will shoot you in the foot if you don't do overflow/buffer size checks)
2) calloc() is ancient, probably pre-dating many virtual memory optimisations, and back then, memory was relatively fast vs instruction execution, so adding calloc() to speed up giant memory allocations would be less impactful. But that's just a hunch, and I'm often surprised by just how sophisticated early UNIX code was. Early computing was slow, every performance gain you could squeeze out of the system mattered and if there were VMs that could defer zeroing memory until it was really needed then people would probably try to do that.
But my guess is, calloc() was simply a helper function, added because it was very common to malloc() some memory and then zero it straight away. Does anyone know the actual history?
- jwilk 4y agoAs others pointed out elsewhere, as as you suspected, early calloc() implementations didn't zero memory or check for overflow. "Why is calloc useful?" would be probably a better title.