realloc((char *)NULL,size) - how standard ?

Steve Summit scs at adam.mit.edu
Sun Feb 24 18:17:16 AEST 1991


In article <1991Feb16.010828.2152 at pscnet.UUCP> kean at pscnet.UUCP (Kean Johnston) writes:
>The other day I had occasion to write a little C program which was repeatedly
>increasing an array. Of course, realloc() is perfect for this.
>...Harbison and Steele... state that if you pass as the first parameter to
>realloc a NULL pointer, then realloc() will allocate a block of size bytes
>for you. No need to malloc the very first block.
>Well, under Xenix 2.3.3 with 2.3.0 DevSys, this isn't so. If you don't do
>the initial [m]alloc of the block, then realloc fails. Is using a NULL pointer
>as the first parameter to realloc() a "standard" feature of the function, and
>if so, which of the plethora of standards?

The Teeming Millions (if I may borrow Cecil Adams' term) are
certainly prescient this month!  This is an excellent question,
and calls for another sneak preview of the upcoming, updated
comp.lang.c frequently-asked questions list:

56.  Is it legal to pass a null pointer as the first argument to
     realloc()?  Why would you want to?

A:   Doing so is legal and portable, at least as of ANSI X3.159's
     ratification.  (Not all pre-ANSI libraries accept it, however.)
     Passing an initially-null pointer to realloc can make it very easy
     to write a self-starting incremental allocation algorithm.

To elaborate, BSD (and perhaps V7) have already had the newly-
standardized behavior, but many other historical systems
(including, I am told, pre-ANSI System V) did not.

                                            Steve Summit
                                            scs at adam.mit.edu

P.S. I'm surprised that Harbison & Steele (2nd Ed.) sanction the
usage, since it was not universal in 1987 when the book was
published.  (I have been burned by the historical inconsistency,
as well.)



More information about the Comp.lang.c mailing list