prev up next   top/contents search

comp.lang.c FAQ list · Question 7.31

Q: What's the difference between calloc and malloc? Which should I use? Is it safe to take advantage of calloc's zero-filling? Does free work on memory allocated with calloc, or do you need a cfree?

A: calloc(m, n) is essentially equivalent to

p = malloc(m * n);
memset(p, 0, m * n);

There is no important difference between the two other than the number of arguments and the zero fill.[footnote]

Use whichever function is convenient. Don't rely on calloc's zero fill too much (see below); usually, it's best to initialize data structures yourself, on a field-by-field basis, especially if there are pointer fields.

calloc's zero fill is all-bits-zero, and is therefore guaranteed to yield the value 0 for all integral types (including '\0' for character types). But it does not guarantee useful null pointer values (see section 5 of this list) or floating-point zero values.

free is properly used to free the memory allocated by calloc; there is no Standard cfree function.

One imagined distinction that is not significant between malloc and calloc is whether a single element or an array of elements is being allocated. Though calloc's two-argument calling convention suggests that it is supposed to be used to allocate an array of m items of size n, there is no such requirement; it is perfectly permissible to allocate one item with calloc (by passing one argument as 1) or to allocate an array with malloc (by doing the multiplication yourself; see for example the code fragment in question 6.14). (Nor does structure padding enter into the question; any padding necessary to make arrays of structures work correctly is always handled by the compiler, and reflected by sizeof. See question 2.13.)

References: ISO Sec. 7.10.3 to
H&S Sec. 16.1 p. 386, Sec. 16.2 p. 386
PCS Sec. 11 pp. 141,142

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North