tom st denis <> writes:
> On Aug 12, 4:47Â*am, Nobody <nob...@nowhere.com> wrote:
>> On Thu, 11 Aug 2011 23:55:45 -0700, lolzy wrote:
>> > Thanks for all your comments. I still have some questions
:
>>
>> > * Why do you prefer malloc() over calloc() ?
>>
>> calloc() zeros the allocated memory, which is inefficient if you don't
>> actually need to do so.
>
> Generally, if you're allocating memory for a struct that has pointers
> calloc() is your buddy since it'll also NULL the pointers [ya ya
> rabble rabble, it's portable, let it go]. If you have char arrays
> they're now NUL terminated, etc and so on...
No, I don't think I will let it go.
The language does not guarantee that either null pointers or
floating-point zero are represented as all-bits-zero.
There wasn't even such a guarantee for integer types until *after*
C99. (As of the C99 standard, an integer representation with padding
bits could in principle require some of those bits to be 1, making
all-bits-zero a trap representation; one of the technical corrigenda
requires all-bits-zero to be a valid representation for 0.)
I don't know of any implementation where all-bits-zero *isn't*
the representation for null pointers, zero-valued integers,
and zero-valued floating-point numbers. So if you use calloc()
and assume that it sets your pointers to NULL, you can almost
certainly get away with it. But your code won't be portable to
any implementations that violate those assumptions.
If you're ok with that, go ahead -- but at least add a comment
exlaining the choice you've made.
*Now* I'll let it go.

}
> If you're just allocating a buffer and then going to immediately use
> it then malloc() is handy.
Why allocate a buffer unless you're going to use it? There are
cases where it's convenient to initialize some large data structure
to all zeros, with the possibility that you'll actually use the zero
values before writing some meaningful value. But another approach
is for your program's logic to keep track of which elements you've
set, and refer only to those elements' values. For example, if
a char array is going to contain a string, you don't need to zero
the whole thing; zeroing the first byte makes it an empty string.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"