venkatesh wrote:
hai to everybody,
i am having doubt in difference between the malloc
and calloc function.
please tell where to use and when to use those functions?
Markus Becker has explained the difference. The second
part of your question is about which function to use under
what circumstances, and my suggestion is "Use malloc() almost
always and calloc() almost never."
The reason is that the initialization to zero that calloc()
performs is usually not very helpful:
- The initialization to "all-bits-zero" is not necessarily
the same as initialization to "all-data-zero." C says
very little about the representation of values in memory,
nothing at all for floating-point or pointer values. On
many machines all-bits-zero representations will in fact
correspond to f.p. zeroes or null pointers, but this is
not guaranteed by the language and there have been machines
where the correspondence did not hold. If you get in the
habit of using calloc() to initialize f.p. and pointer
items, you may be heading for trouble.
- Usually, one allocates a chunk of dynamic memory in order
to store something in it -- and when you store something
in it, you'll overwrite whatever was there before. Thus,
the initialization performed by calloc() is usually not
needed anyhow. There are occasional exceptions where all-
bits-zero initialization is helpful, but they are unusual.
Not unheard-of, I grant, but unusual.
There's one possible advantage I can imagine for calloc() over
malloc(), and that's the opportunity for a tiny bit of sanity-
checking. Here are two ways you might try to allocate memory to
hold N items of SomeType:
SomeType *p = malloc(N * sizeof *p);
SomeType *q = calloc(N, sizeof *q);
Now, if N is so large that multiplying it by sizeof(SomeType)
exceeds the valid range of size_t, the argument in the first
form will "wrap around" and you'll silently request less memory
than you wanted; if the request succeeds you'll proceed merrily
along and try to store N items in too small a space, with the
usually unhappy and sometimes baffling consequences. The second
form, however, will fail and return NULL so your program will be
alerted that the space was not available; there'll be no silent
error. However, this seems to me to be a very small advantage,
so I'll stick with my original suggestion: malloc() almost always,
calloc() almost never.
--
Eric Sosman
es*****@acm-dot-org.invalid