realloc

John Sahr johns at calvin.EE.CORNELL.EDU
Fri Mar 31 00:08:40 AEST 1989


In article <10032 at ihlpb.ATT.COM> gregg at ihlpb.ATT.COM (Wonderly) writes:
>From article <10170 at bloom-beacon.MIT.EDU>, by scs at adam.pika.mit.edu (Steve Summit):
[ Mr. Summit complains that ptr = realloc(ptr,nbytes) does not behave like 
ptr = malloc(nbytes) when ptr is NULL. ]

>I read the man page for realloc and it said nothing about this...

There are two different reallocs on my system, the usual realloc(3c) and
another realloc(3x).  Neither one specifies the behaviour of realloc()
when ptr is NULL.  The man for realloc(3x) says "undocumented features
of malloc(3c) have not been duplicated." Not realloc(3c), but malloc(3c).

My realloc(3c) man does say that it will handle a pointer to a block that
was previously free(3c)'d.  

I have been working on a program recently where realloc became quite 
handy.  After a while, I realized that every place I used realloc, I was
also using malloc, a la

>Is it not possible for you to type
>
>	if (ptr == NULL)
>		ptr = malloc (nbytes);
>	else
>		ptr = realloc (ptr, nbytes);
>
>or are you one of those people that assumes (*((char *)NULL) == 0) too?

So, I tried using ptr = realloc(ptr,nbytes) without the ptr == NULL check.
It worked, at least for (3c).  But Mr. Wonderly is correct to the extent
this behaviour is not documented in the man pages, and therefore _should
not be relied upon_.

>This damn lazy programming and sorry excuses for not being defensive has
>got to stop.  Hiding all of the magic in the inards of the implementation
>does not make it any easier for people to understand the code! 

True enough, in general.  In this case, however, it seems "clear" to me 
what is going on.  If you never rely on the ptr == NULL behaviour, you 
can still write if(ptr == NULL).....else....., and it will do the same 
thing, and be "clear."  Clarity, however, is in the eye of the beholder, as 
the discussion on indentation and bracket location indicated a few months
back.

As far as the magic in the innards, it strikes me that realloc(3c)'s
function of copying the old contents into the possibly moved and different
sized block is more "magical" than behaving like malloc(3c) if ptr == NULL.
One could always call memcpy() if one wanted to be more "clear" when this
behaviour is needed.

[deletions]
>Gregg Wonderly                             DOMAIN: gregg at ihlpb.att.com
>AT&T Bell Laboratories                     UUCP:   att!ihlpb!gregg



-- 
John Sahr,                          School of Elect. Eng.,  Upson Hall   
                                    Cornell University, Ithaca, NY 14853

ARPA: johns at calvin.ee.cornell.edu; UUCP: {rochester,cmcl2}!cornell!calvin!johns



More information about the Comp.std.c mailing list