... while we're on the subject I'd like to ask about something
that's been niggling me for a while now.
One of my C programming books (A Book On C 4th edition, Kelley &
Pohl) has the following to say about malloc and calloc (page 663):
[wording snipped, but calloc()'s description contains the word
"contiguous" while malloc()'s does not]
The niggle of which I speak is with respect to the "contiguous" part of the
calloc description; is the space allocated by a successful malloc call not
necessarily required to be contiguous?
Both return a contiguous memory region.
The calloc() description is "more deserving" of the extra word for
one simple reason: malloc() gets only one parameter -- the number
of bytes to allocate -- while calloc() gets two. Since "there is
no magic" (or was, at least, when C was first being written -- ISO
now allows arbitrary amounts of magic to occur between the compiler
and its Standard C library), a call of the form:
malloc(32)
is unable to tell whether you wanted 8 four-byte objects (e.g.,
malloc(n_obj * sizeof *obj) where n_obj is 8 and sizeof *obj is 4)
or whether you wanted a single 32-byte object (e.g.,
malloc(sizeof *obj2) where sizeof *obj2 is 32). On the other
hand, calloc gets a separate "number of objects" and "size of
each object":
calloc(n_obj, sizeof *obj) /* for the first case */
vs calloc(1, sizeof *obj2) /* for the second case */
Obviously calloc() has more information than malloc() -- so it
might, conceivably, be able to use that to call malloc() N times
instead of just once (and indeed, there was once a cfree() that
was to be used on calloc()'ed memory, and perhaps cfree() might
then call free() N times as well). If calloc() were allowed to
do that, it could get N discontiguous regions, and perhaps
chain them together into a linked list or something.
It does not do that, of course; and you free() the pointers you
get from calloc() just as you free() those from malloc(), so calloc()
just has to multiply its two parameters together (and check for
overflow). But because calloc() has, at first glance, enough
information to malloc() N times, the extra word "contiguous" has
some reason for being there, however weak that reason turns out to
be in the end.