malloc(0) (Was: realloc)

Doug Gwyn gwyn at smoke.BRL.MIL
Tue Apr 4 04:56:35 AEST 1989


In article <9132 at alice.UUCP> andrew at alice.UUCP (Andrew Hume) writes:
>the ONLY justification put forward is some stuff about zero-sized
>objects (gwyn admits to being the point of contact). the only
>point actually mentioned is devising semantics for zero-sized objects; ...

I believe that was in fact the only technical issue involved in the
decision to permit malloc(0) to fail for reasons other than running out
of memory.  There were several X3J11 members who, rightly recognizing
that if the standard permitted portable programs to rely on malloc(0)
succeeding under normal circumstances it would also have to address the
issue of semantics for 0-sized objects, balked at having to cross that
threshold.  I'm a big fan of 0-sized objects, but I've become convinced
that formally recognizing them would have significant impact in several
places in the standard.  The amount of work to get all the technical
points right was considered more than could be justified simply to
support the style of malloc() usage you're interested in.

Incidentally, our last-minute reworking of the wording about last-plus-
one element of arrays, etc. may have provided most of the scaffolding
needed to formally support 0-sized objects as well.  However, 0-sized
objects could not be allowed without explicit full committee action,
since they had been explicitly disallowed in previous voting.

Some people might make the argument that it is more likely when malloc()
is called with a 0 size request that there is a bug in the program than
that it is a consistent and sensible thing to be attempting.  Certainly
it COULD be used for legitimate purposes as Andrew apparently does, but
most of the malloc() applications I've seen are already in trouble if
they get to the point where they would be malloc(0)ing.  Thus I don't
think the ANSI-portable malloc() behavior poses a significant problem.

#define	myalloc(n)	malloc((n)?(n):1)



More information about the Comp.lang.c mailing list