Source-Changes-HG archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

[src/trunk]: src/lib/libc/stdlib Steal the "malloc() vs. calloc()" -idiom fro...



details:   https://anonhg.NetBSD.org/src/rev/2f2d0a04cacf
branches:  trunk
changeset: 754430:2f2d0a04cacf
user:      jruoho <jruoho%NetBSD.org@localhost>
date:      Fri Apr 30 07:00:51 2010 +0000

description:
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.

diffstat:

 lib/libc/stdlib/malloc.3 |  27 +++++++++++++++++++++++++--
 1 files changed, 25 insertions(+), 2 deletions(-)

diffs (48 lines):

diff -r 4a8b669cef66 -r 2f2d0a04cacf lib/libc/stdlib/malloc.3
--- a/lib/libc/stdlib/malloc.3  Fri Apr 30 06:54:16 2010 +0000
+++ b/lib/libc/stdlib/malloc.3  Fri Apr 30 07:00:51 2010 +0000
@@ -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



Home | Main Index | Thread Index | Old Index