Source-Changes-HG archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
[src/trunk]: src/lib/libc/stdlib add warning on realloc() size de-synchroniza...
details: https://anonhg.NetBSD.org/src/rev/1766dd9a5105
branches: trunk
changeset: 552107:1766dd9a5105
user: itojun <itojun%NetBSD.org@localhost>
date: Fri Sep 19 05:36:59 2003 +0000
description:
add warning on realloc() size de-synchronization. from openbsd
diffstat:
lib/libc/stdlib/malloc.3 | 18 ++++++++++++------
1 files changed, 12 insertions(+), 6 deletions(-)
diffs (52 lines):
diff -r 1b78c3e6917b -r 1766dd9a5105 lib/libc/stdlib/malloc.3
--- a/lib/libc/stdlib/malloc.3 Fri Sep 19 05:33:15 2003 +0000
+++ b/lib/libc/stdlib/malloc.3 Fri Sep 19 05:36:59 2003 +0000
@@ -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 @@
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
Home |
Main Index |
Thread Index |
Old Index