Module Name:    src
Committed By:   pooka
Date:           Mon Jul 20 12:10:03 UTC 2009

Modified Files:
        src/lib/libc/stdlib: malloc.3

Log Message:
Re-add explanation of how to correctly use realloc.


To generate a diff of this commit:
cvs rdiff -u -r1.29 -r1.30 src/lib/libc/stdlib/malloc.3

Please note that diffs are not public domain; they are subject to the
copyright notices on the relevant files.

Modified files:

Index: src/lib/libc/stdlib/malloc.3
diff -u src/lib/libc/stdlib/malloc.3:1.29 src/lib/libc/stdlib/malloc.3:1.30
--- src/lib/libc/stdlib/malloc.3:1.29	Mon May 18 09:00:02 2009
+++ src/lib/libc/stdlib/malloc.3	Mon Jul 20 12:10:03 2009
@@ -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 @@
 .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

Reply via email to