realloc

Walter Bright bright at Data-IO.COM
Sat Apr 1 05:52:35 AEST 1989


In article <9118 at alice.UUCP< ark at alice.UUCP (Andrew Koenig) writes:
<In article <10032 at ihlpb.ATT.COM<, gregg at ihlpb.ATT.COM (Wonderly) writes:
<< I read the man page for realloc and it said nothing about this.  Is it
<< not possible for you to type
<< 	if (ptr == NULL)
<< 		ptr = malloc (nbytes);
<< 	else
<< 		ptr = realloc (ptr, nbytes);
<Hm.  Here's what my draft ANSI C spec has to say about realloc:
<	[stuff deleted]
<Of course, not all C implementations behave this way.  This
<leaves C programmers in a bind: rely on this behavior or not?  If
<not, how does one determine which behavior can be trusted?  If
<so, what does one do when one's code breaks on various machines?

I am involved daily with porting code between PCs, Suns, Apples, Vaxes,
etc. The quality of C compilers varies widely, as does the conformance
to ANSI C. What I have done is create a file called 'missing.c' in
which I write functional equivalents of ANSI C library functions. They
are #ifdef'd in for those primitive compilers that don't have them.
For instance, BSD Unix doesn't have memcpy, so I have:

#if BSDUNIX || VAX11C
char *memcpy(t,f,n)
#if BSDUNIX
char *t,*f;
int n;
{
	bcopy(f,t,n);
	return t;
}
#else
register char *t,*f;
register int n;
{
	char *retval = t;

	while (n--) *t++ = *f++;
	return retval;
}
#endif
#endif

(VAX11C is my euphamism for DEC's C compiler.)

I have dealt with the primitive realloc's by always using a function
mem_realloc, and defining it as:

#if __STDC__
#define mem_realloc realloc
#else
void *mem_realloc(oldmem_ptr,newnumbytes)
void *oldmem_ptr;
unsigned newnumbytes;
{   extern void *realloc(),*malloc();
    void *p;

    if (oldptr == NULL)
	p = newnumbytes ? malloc(newnumbytes) : NULL;
    else if (newnumbytes == 0)
    {	free(oldptr);
	p = NULL;
    }
    else
	p = realloc(oldptr,newnumbytes);
    /*printf("realloc(x%lx,%d) = x%lx\n",oldptr,newnumbytes,p);*/
    return p;
}
#endif

If I'm using a compiler which has a broken realloc(), (which is common!)
I can reimplement my mem_realloc as using a malloc/memcpy/free combination.

Using this approach I can use ANSI library function semantics and still
work with archaic compilers. The application code doesn't have to be
littered with crutches for this stuff, it's isolated away.



More information about the Comp.lang.c mailing list