add warning on realloc() size de-synchronization. from openbsd

This commit is contained in:
itojun 2003-09-19 05:36:59 +00:00
parent 6e4e427990
commit 57e4de6099

View File

@ -1,4 +1,4 @@
.\" $NetBSD: malloc.3,v 1.20 2003/08/07 16:43:41 agc Exp $
.\" $NetBSD: malloc.3,v 1.21 2003/09/19 05:36:59 itojun Exp $
.\"
.\" Copyright (c) 1980, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
@ -34,7 +34,7 @@
.\" @(#)malloc.3 8.1 (Berkeley) 6/4/93
.\" From FreeBSD: Id: malloc.3,v 1.18 1999/03/28 14:16:04 phk Exp
.\"
.Dd August 11, 2002
.Dd September 19, 2003
.Dt MALLOC 3
.Os
.Sh NAME
@ -126,23 +126,29 @@ When using
one must be careful to avoid the following idiom:
.Pp
.Bd -literal -offset indent
nsize += 50
if ((p = realloc(p, nsize)) == NULL)
return NULL;
return (NULL);
.Ed
.Pp
In most cases, this will result in a leak of memory.
Do not adjust the variable describing how much memory has been allocated
until one knows the allocation has been successful.
This can cause aberrant program behavior if the incorrect size value is used.
In most cases, the above sample will also result in a leak of memory.
As stated earlier, a return value of
.Dv NULL
indicates that the old object still remains allocated.
Better code looks like this:
.Bd -literal -offset indent
if ((p2 = realloc(p, nsize)) == NULL) {
newsize = size + 50;
if ((p2 = realloc(p, newsize)) == NULL) {
if (p)
free(p);
p = NULL;
return NULL;
return (NULL);
}
p = p2;
nsize = newsize;
.Ed
.\"XXX".Pp
.\"XXX"The