[comp.lang.c] malloc+copy+free vs realloc

chris@mimsy.UUCP (Chris Torek) (10/29/88)

In article <1730@dataio.Data-IO.COM> bright@Data-IO.COM (Walter Bright) writes:
-I've seen a number of people say that the following:
-	p = realloc(p,newsize);
-	assert(p);			/* fail if out of memory */
-is slower and/or less maintainable than:
-	newp = malloc(newsize);
-	assert(newp);			/* fail if out of memory */
-	memcpy(newp,p,(newsize < oldsize ? newsize : oldsize));
-	free(p);
-	oldsize = newsize;
-	p = newp;

Obviously this is false.  There is, however, one case where I do use
malloc+copy+free instead of realloc:  If the data are important and
must not be destroyed by a failed realloc.  The draft standard says
that this is already so; but I have my doubts about current implementations.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris

bright@Data-IO.COM (Walter Bright) (11/01/88)

In article <14232@mimsy.UUCP> chris@mimsy.UUCP (Chris Torek) writes:
>There is, however, one case where I do use
>malloc+copy+free instead of realloc:  If the data are important and
>must not be destroyed by a failed realloc.  The draft standard says
>that this is already so; but I have my doubts about current implementations.

In which case, as I said, you write your own realloc(), as in:

#if BADREALLOC
extern void *mem_realloc();
#else
#define mem_realloc(p,oldsize,newsize)	realloc((p),(newsize))
#endif

and write my_realloc to do the malloc/copy/free. This gives you the advantage
of using a well-implemented realloc with a fallback to your own if the system
one is bad.

I have used a (slightly more complex) variation on this for all my software
for years, and have been pleased with the results. I try to code in ANSI
as much as possible, and use the macro preprocessor for compatibility with
stone age compilers. I also port the ANSI library routines when I need them
for some port, instead of trying to do without them.