Module Name: src
Committed By: jruoho
Date: Fri Apr 30 07:00:51 UTC 2010
Modified Files:
src/lib/libc/stdlib: malloc.3
Log Message:
Steal the "malloc() vs. calloc()" -idiom from the OpenBSD's malloc(3).
While it may be debated how useful this is, good idiomatic usage examples
are exactly the kind of thing one would hope to see more in manual pages.
To generate a diff of this commit:
cvs rdiff -u -r1.30 -r1.31 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.30 src/lib/libc/stdlib/malloc.3:1.31
--- src/lib/libc/stdlib/malloc.3:1.30 Mon Jul 20 12:10:03 2009
+++ src/lib/libc/stdlib/malloc.3 Fri Apr 30 07:00:51 2010
@@ -1,4 +1,4 @@
-.\" $NetBSD: malloc.3,v 1.30 2009/07/20 12:10:03 pooka Exp $
+.\" $NetBSD: malloc.3,v 1.31 2010/04/30 07:00:51 jruoho 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 June 20, 2009
+.Dd April 30, 2010
.Dt MALLOC 3
.Os
.Sh NAME
@@ -78,6 +78,29 @@
with the exception that the allocated memory is explicitly initialized
to zero bytes.
.Pp
+When using
+.Fn malloc
+be careful to avoid the following idiom:
+.Bd -literal -offset indent
+if ((p = malloc(number * size)) == NULL)
+ err(1, "malloc");
+.Ed
+.Pp
+The multiplication may lead to an integer overflow.
+To avoid this,
+.Fn calloc
+is recommended.
+.Pp
+If
+.Fn malloc
+must be used, be sure to test for overflow:
+.Bd -literal -offset indent
+if (size && number > SIZE_MAX / size) {
+ errno = ENOMEM;
+ err(1, "overflow");
+}
+.Ed
+.Pp
The
.Fn realloc
function changes the size of the previously allocated memory referenced by