3 ms·
Yes, if you know you want zeroed memory, calloc() is best: because a smart userspace allocator will have two paths: if it is able to re-use memory already alloc
by BeeOnRope 7y ago
Yes, if you know you want zeroed memory, calloc() is best: because a smart userspace allocator will have two paths: if it is able to re-use memory already allocated and freed from userspace, it will explicitly zero it (probably with a memset) since it it is not (guaranteed to be) zero.
OTOH, if it is asking the OS for fresh memory to satisfy the request, or is satisfying the request from an earlier allocation returned by the OS (which hasn't yet been fully used), it knows the memory is zero and can just return it directly. In that scenario calloc() is as fast as malloc(), yet it provides the additional guarantee of zeroed memory.
Unfortunately, calloc() and C++ don't really place nice together, and C++ has no equivalent concept to calloc() in its allocator model (the same complaint applies to realloc() which would otherwise be very useful).