realloc

Steve Summit scs at adam.pika.mit.edu
Wed Mar 29 12:07:46 AEST 1989


Today, for the third time in half as many years, I got badly
burned, and wasted lots of time, due to a bug in a certain
vendor's implementation of realloc.  It is an apparently well-
kept secret that realloc is supposed to behave gracefully at
a slightly special-cased boundary point: when handed a NULL
pointer and a nonzero size, it acts essentially as a malloc.

If you have ever implemented a C run-time library, or if you are
implementing one now, or if you may ever implement one, or if you
know anyone who falls into any of these categories, pay attention:
begin your realloc() implementation with the equivalent of:

	char *realloc(ptr, size)
	char *ptr;
	int size;
	{
	if(ptr == NULL)
		return malloc(size);
	...

The ptr argument and realloc's return value may be void *'s, and
the size argument may be an unsigned or a size_t; the essential
point I am making is the test for NULL and the call of malloc.

This is a short message, so that people who don't read long
articles will see it.  I'll hold further explanations and
justifications for another day.

                                            Steve Summit
                                            scs at adam.pika.mit.edu



More information about the Comp.std.c mailing list