realloc reactions ??

Peter S. Shenkin shenkin at cunixf.cc.columbia.edu
Sat Feb 16 08:37:47 AEST 1991


In article <4786 at network.ucsd.edu> slamont at network.ucsd.edu (Steve Lamont) writes:
>In article <9102150952.AA24219 at karron.med.nyu.edu> karron at cmcl2.nyu.edu writes:
>>
>>I am curious about the realloc() function. 
>
>Me too, but for a different reason than Dan.  Why does SGI's realloc() barf on
>a null pointer....

C'mon, you're not serious, are you?  Realloc() expects its first arg to be
a pointer to some block of storage.  For example, the man page (IRIX 3.2.1)
says, "The contents [of the new storage allocated] will be unchanged up to the
lesser of the new and old sizes".  If the first arg of realloc() doesn't point
to anything, clearly the result is undefined.  And NULL, of course, cannot point
to anything.  (Other peoples' man pages explicitly state that realloc()'s first
arg must be a pointer previously returned by malloc, calloc or realloc.)

Now let me guess why you're trying to do this.  You have a routine in which
you're trying to allocate new storage each time you come in.  The first time
you want to malloc(), and subsequent times you want to realloc(), perhaps to
grow an array from size zero up to some ultimate size that is unknown until
the program runs.  So you figure that doing a realloc() with NULL as a first
arg is as good a way as doing malloc() as any other.  Sorry, no can do!  In
this situation I usually something like:

	....
	int nbyte;		/* additional bytes to be allocated now */
	int nptr = 0;		/* number of bytes now pointed to by ptr */
	char *ptr = NULL;
	....
	if( ptr == NULL )
		ptr = malloc( (unsigned)nbyte );
	else {
		ptr = realloc( ptr, (unsigned)(nptr + nbyte) );
	}
	assert( ptr != NULL );	/* make sure alloc worked */
	nptr += nbyte;
	....
************************f*u*cn*rd*ths*u*cn*gt*a*gd*jb**************************
Peter S. Shenkin, Department of Chemistry, Barnard College, New York, NY  10027
(212)854-1418  shenkin at cunixf.cc.columbia.edu(Internet)  shenkin at cunixf(Bitnet)
***"In scenic New York... where the third world is only a subway ride away."***



More information about the Comp.sys.sgi mailing list