diff options
| author | jruoho <jruoho@NetBSD.org> | 2010-04-30 07:00:51 +0000 |
|---|---|---|
| committer | jruoho <jruoho@NetBSD.org> | 2010-04-30 07:00:51 +0000 |
| commit | 75d4d306c546d2eb68e12279bbf5455cd42796e2 (patch) | |
| tree | e37352605d895e03b6c4091d85e7fb21d1b8d0b1 /lib/libc/stdlib | |
| parent | 779fbbb100fd2f038b93065d68324f937d5e60cf (diff) | |
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 (limited to 'lib/libc/stdlib')
| -rw-r--r-- | lib/libc/stdlib/malloc.3 | 27 |
1 files changed, 25 insertions, 2 deletions
diff --git a/lib/libc/stdlib/malloc.3 b/lib/libc/stdlib/malloc.3 index 012c4d6982d..02361549fe2 100644 --- a/lib/libc/stdlib/malloc.3 +++ b/lib/libc/stdlib/malloc.3 @@ -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 an argument of 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 |
