malloc vs calloc and invalid pointers

Chris Torek chris at mimsy.UUCP
Sun Sep 25 15:44:06 AEST 1988


In article <706.2339B3DF at stjhmc.fidonet.org>
will.summers at p6.f18.n114.z1.fidonet.org (will summers) writes:
>This got me thinking about a subtle dpANS wording difference:
>
>    struct _whatever *pstruct;
>
>    pstruct = (struct _whatever *) malloc (n * sizeof(struct _whatever));
>
>is pstruct[n-1] or pstruct+(n-1) -guaranteed- to be allowed on
>-all- dpANS conformant installations?

Assuming that malloc did not return NULL, yes.  If it did not you would
not have allocated at least n*sizeof(struct _whatever) bytes.
(Incidentally, `_' marks a reserved name space.)  Rephrasing the
question as `is &pstruct[n] legally computable', the answer is still
yes.

>I guess it comes down to this: does dpANS -guarantee- an object is
>divisable into sub-objects following Chris Torek's "locally
>flat" paradigm, and that pointers produced by arithmetic on 
>pointers to the sub-objects will be valid.

A `malloc'ed object, yes; at least, that was certainly the intention.

>Simply stated, does dpANS wording imply any difference between
>calloc (n, size) and  malloc (n*size) ?

Other than that calloc fills the allocated memory with zero bytes,
there is no guaranteed difference.  It is possible that one or the
other might be preferable on some architecture (calloc is often just
malloc+memset in disguise, but on some machine calloc might be able to
use less space, since it gets more information), but there is no
predicting which is best where, and either is correct.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list