Tweaks to malloc(3) manpage

2015-11-01 Thread Michael McConville
1. I don't see much reason to mention calloc() as an alternative to
reallocarray() when it's the worse option.

2. Use size > 0 when testing overflow.

ok?


Index: lib/libc/stdlib/malloc.3
===
RCS file: /cvs/src/lib/libc/stdlib/malloc.3,v
retrieving revision 1.91
diff -u -p -r1.91 malloc.3
--- lib/libc/stdlib/malloc.314 Sep 2015 13:08:01 -  1.91
+++ lib/libc/stdlib/malloc.31 Nov 2015 16:35:17 -
@@ -203,10 +203,6 @@ if ((p = reallocarray(NULL, num, size)) 
err(1, "reallocarray");
 .Ed
 .Pp
-Alternatively,
-.Fn calloc
-may be used at the cost of initialization overhead.
-.Pp
 When using
 .Fn realloc ,
 be careful to avoid the following idiom:
@@ -291,7 +287,7 @@ size_t num, size;
 \&...
 
 /* Check for size_t overflow */
-if (size && num > SIZE_MAX / size)
+if (size > 0 && num > SIZE_MAX / size)
errc(1, EOVERFLOW, "overflow");
 
 if ((p = malloc(size * num)) == NULL)
@@ -309,7 +305,7 @@ if (size < 0 || num < 0)
errc(1, EOVERFLOW, "overflow");
 
 /* Check for signed int overflow */
-if (size && num > INT_MAX / size)
+if (size > 0 && num > INT_MAX / size)
errc(1, EOVERFLOW, "overflow");
 
 if ((p = malloc(size * num)) == NULL)



Re: Tweaks to malloc(3) manpage

2015-11-01 Thread Theo de Raadt
> 1. I don't see much reason to mention calloc() as an alternative to
> reallocarray() when it's the worse option.

calloc() still remains the portable option.  Something should probably
still be mentioned here, otherwise people fall back to unchecked
malloc -- no matter what is stated further below regarding overflow
checks.

> 2. Use size > 0 when testing overflow.

That feels wrong.  The size variables in some code contexts may
mistakenly be signed, yet assigned an unsigned value from a caller.
You are trying to fight a losing battle with undefined behaviour
handling in modern compilers, and programmers who don't have time to
use static analysis tools.  In case size is signed, it would be better
to FAIL the overflow check as happens currently, rather multiply a
negative number, end up with a result, malloc, and then screw things up.