summaryrefslogtreecommitdiff
path: root/lib/libc/stdlib/malloc.3
diff options
context:
space:
mode:
authorpooka <pooka@NetBSD.org>2009-07-20 12:10:03 +0000
committerpooka <pooka@NetBSD.org>2009-07-20 12:10:03 +0000
commitc6181c7b2f48e91cac61700d108ce90d6c44ede1 (patch)
tree5456a2c4e64fd017b3a2fcb060507f3581c7ef32 /lib/libc/stdlib/malloc.3
parent5c2940d31a74730c04f035337939ee6e9c03f1bd (diff)
Re-add explanation of how to correctly use realloc.
Diffstat (limited to 'lib/libc/stdlib/malloc.3')
-rw-r--r--lib/libc/stdlib/malloc.334
1 files changed, 32 insertions, 2 deletions
diff --git a/lib/libc/stdlib/malloc.3 b/lib/libc/stdlib/malloc.3
index c35ca8917a5..012c4d6982d 100644
--- a/lib/libc/stdlib/malloc.3
+++ b/lib/libc/stdlib/malloc.3
@@ -1,4 +1,4 @@
-.\" $NetBSD: malloc.3,v 1.29 2009/05/18 09:00:02 wiz Exp $
+.\" $NetBSD: malloc.3,v 1.30 2009/07/20 12:10:03 pooka 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
.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.73 2007/06/15 22:32:33 jasone Exp $
.\"
-.Dd October 15, 2007
+.Dd June 20, 2009
.Dt MALLOC 3
.Os
.Sh NAME
@@ -106,6 +106,36 @@ function behaves identically to
.Fn malloc
for the specified size.
.Pp
+When using
+.Fn realloc
+one must be careful to avoid the following idiom:
+.Pp
+.Bd -literal -offset indent
+nsize += 50;
+if ((p = realloc(p, nsize)) == NULL)
+ return (NULL);
+.Ed
+.Pp
+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
+newsize = size + 50;
+if ((p2 = realloc(p, newsize)) == NULL) {
+ if (p)
+ free(p);
+ p = NULL;
+ return (NULL);
+}
+p = p2;
+size = newsize;
+.Ed
+.Pp
The
.Fn free
function causes the allocated memory referenced by