Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 20 Aug 1998 13:49:38 -0600
From:      Nate Williams <nate@mt.sri.com>
To:        Warner Losh <imp@village.org>
Cc:        hackers@FreeBSD.ORG
Subject:   Re: Realloc fix for review
Message-ID:  <199808201949.NAA08010@mt.sri.com>
In-Reply-To: <199808201619.KAA20970@harmony.village.org>
References:  <199808201619.KAA20970@harmony.village.org>

next in thread | previous in thread | raw e-mail | index | archive | help
> Recently, OpenBSD went through their source tree and fixed all
> instances of
> 	a = realloc(a, size);
> with
> 	na = realloc(a, size);
> 	if (!na)
> 		free(a);
> 	a = na;

I just went through the manpage, and it appears that this code is in
fact in-correct.

     The realloc() function changes the size of the previously allocated memo-
     ry referenced by ptr to size bytes.  The contents of the memory are un-
     changed up to the lesser of the new and old sizes.  If the new size is
     larger, the value of the newly allocated portion of the memory is unde-
     fined.  If the requested memory cannot be allocated, NULL is returned and
     the memory referenced by ptr is valid and unchanged.  If ptr is NULL, the
     realloc() function behaves identically to malloc() for the specified
     size.

So, assuming we want a smaller chunk, then we can potentally end up with
the old chunk back.  The return is successful, and we end up freeing
it. :(

It is also possible to return the same pointer back to us, (we just
extended the bucket), and we end up freeing the valid pointer.

Finally, if NULL is returned, then it's up to the coder to 'Do The Right
Thing', and we've violated POLA.

In short, I think it's the *wrong* thing to do, and has too many worse
side-effects than the original code.



Nate

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199808201949.NAA08010>