Path: utzoo!utgpu!water!watmath!clyde!att!rutgers!uwvax!oddjob!mimsy!chris
From: chris@mimsy.UUCP (Chris Torek)
Newsgroups: comp.lang.c
Subject: malloc vs calloc and invalid pointers
Message-ID: <13731@mimsy.UUCP>
Date: 25 Sep 88 05:44:06 GMT
References: <706.2339B3DF@stjhmc.fidonet.org>
Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742
Lines: 36

In article <706.2339B3DF@stjhmc.fidonet.org>
will.summers@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@mimsy.umd.edu	Path:	uunet!mimsy!chris