realloc

Wonderly gregg at ihlpb.ATT.COM
Mon Apr 3 06:00:47 AEST 1989


>From article <9964 at smoke.BRL.MIL>, by gwyn at smoke.BRL.MIL (Doug Gwyn ):
> In article <9122 at alice.UUCP> andrew at alice.UUCP (Andrew Hume) writes:
>>gregg townsend reminds us of the pANS ``feature'' that malloc(0) returns NULL.
>>can anyone provide the (or any) justification of this pointless stupid
>>definition?
> 
> Sure.  malloc() either fails or it succeeds.  If it were required to
> succeed for a 0-sized allocation attempt, then additional semantics
> would have had to have been devised to deal with the 0-sized object
> pointed to by the returned non-null pointer.  For example, should
> a series of malloc(0) calls return distinct pointers?  Anyway, for
> the limited additional functionality this was considered too big a
> can of worms to open.

The use of malloc (0) may exist.  But I have always, and will always continue
to use

	if (nbytes == 0)
		nbytes = 1;

	if (ptr == NULL)
		ptr = (some cast) malloc (nbytes);
	else
		ptr = (some cast) realloc (ptr, nbytes);

When the sequence occurs a lot, I put it into a function.  For crissake,
this is not a "gee look at the benefits this feature provides" issue!  It
is a "gee look at how so many more portability issues are going to pop up"
issue!  And a stupid one at that!

Allocating a small amount of data to point a pointer into so that it is
non-null is going to save a large amount of code space and special case
code all through programs that deal with dynamic objects.

Changing one of the basic library routine interfaces is always a bad
idea, and it always will be!

-- 
Gregg Wonderly                             DOMAIN: gregg at ihlpb.att.com
AT&T Bell Laboratories                     UUCP:   att!ihlpb!gregg



More information about the Comp.lang.c mailing list