Is malloc() or calloc() "better"?
Leo de Wit
leo at philmds.UUCP
Sun Jan 8 00:36:15 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:
|> Most often, once an object is allocated, it is filled with meaningful
|> contents. Seldom is what calloc() would have provided the appropriate
|> contents for the object, so using calloc() would waste CPU time to no
|
|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!
Why should you want to use the value of a variable that was never
assigned to? This is the same mistake as something like:
void foo()
{
int i;
if (i == 0) {
printf("The auto variable was zero\n");
} else {
printf("The auto variable was %d\n",i);
}
}
$ lint foo.c
foo.c:
foo.c(5): warning: i may be used before set <==
foo defined( foo.c(2) ), but never used
printf returns value which is always ignored
|calloc, although more time consuming (not very much) insures empty or zero
|filled memory.
Fact is that the zero-filled area is often worthless, as many others
pointed out: objects are not assigned null values (at least not
portably), and why prefilling with zero bits an object that you are
going to assign a new value to anyway.
If you're talking about relative speeds malloc / calloc, you could be
very surprised; calloc could be an order of magnitude slower, if malloc
for instance does something like taking a block from a free block list
(maintaining free block lists with block sizes equal to a power of 2).
Well, it depends ...
Leo.
More information about the Comp.lang.c
mailing list