It's not better if the program immediately sets the contents to some
other value. Indeed it's worse, since you've just wasted cycles and
potentially lost locality of reference. If you're using a system
with lazy allocation, you've also just potentially committed a lot of
pages that you might not actually need.
values,
Unless of course the zeroed memory was to hold a set of pointers and a
non null value indicates a valid pointer.
That's what we call a "bug". It's excluded by Richard Tobin's
explicit condition "has no bugs".
And zeroing memory, as calloc does, is not guaranteed to produce a
null pointer value, as I'm sure other people have already pointed
out.
But this does not in any way invalidate the need/requirement for auto
zeroing in a memory allocation call.
That's true in a strictly limited sense (if there is any such
requirement, which frankly I do not believe is often the case).
However, the existence of any such requirement equally does not
remove the justification Richard Tobin described for *not*
initializing memory.
Far better, in most cases, that the program allocate memory and then
immediately initialize it explicitly and properly in a type-safe
manner. (Note that may not entail touching every single byte as
calloc does; the data structure being allocated may use a sentinel or
some other length indicator to separate valid from invalid data.)
That way, the program can do just as much work as necessary; it can
commit just as much memory as necessary; it can initialize each field
correctly; it can let the compiler catch certain errors; and it can
document its intentions for maintainers.
The only case where calloc has any advantage, as far as I can tell,
is if a program actually needs to set an entire allocated area to
all-bits-zero, and this happens in a performance-critical area,
because it's conceivable that there might be some small performance
benefit in that case. But if memory allocation is being done in a
performance-critical area there are likely other more significant
optimizations to be made.
--
Michael Wojcik (e-mail address removed)
An intense imaginative activity accompanied by a psychological and moral
passivity is bound eventually to result in a curbing of the growth to
maturity and in consequent artistic repetitiveness and stultification.
-- D. S. Savage