Is malloc() or calloc() "better"?
Michael Paul Hunter
bagpiper at oxy.edu
Mon Jan 9 05:43:17 AEST 1989
In article <620 at usl.usl.edu> pcb at usl.usl.edu (Peter C. Bahrs) writes:
>In article <9254 at smoke.BRL.MIL>, gwyn at smoke.BRL.MIL (Doug Gwyn ) writes:
>> In article <gables.416 at umigw.miami.edu> slores%gables.span at umigw.miami.edu (Stanislaw L. Olejniczak) writes:
>> >It seems to me that most programmers, in giving examples here, use malloc()
>> >please enlighten me why is malloc so much more popular?
>>
stuff....
>What if you dynamically allocate strings and use malloc?... there may or may
>not be a \0 in string[0]...I doubt it? Therefore an initial call to
>if (strcmp(string,"")) may or may not return true!
>
>calloc, although more time consuming (not very much) insures empty or zero
>filled memory.
ouch!!! Anybody who uses calloc for the side effect that they can then
consider that piece of memory to be a null terminated string is asking
for a headache in the future. What happens when the next person inherits
your code and has to speed it up? That person changes the callocs to mallocs
and causes a bug (a naive one, but a bug). What about if that person pulls
the *alloc out of the inner loop....your calloc only helps on the first
iteration... I think it would be better (and faster) to malloc and set the
first element of the array to (char)NULL if you want it to be a 0 length
string....make it a SLM if you are really emphatic.
Mike
More information about the Comp.lang.c
mailing list