I agree it can overflow. But if you use the same variables with the same
values plugged into

ptr = calloc(nmemb, size);

as you use in

freezero(ptr, (size_t)nmemb * size);

If it can overflow, it will have done it already in calloc().


On Fri, Feb 19, 2021 at 12:23 PM Todd C. Miller <todd.mil...@sudo.ws> wrote:

> On Fri, 19 Feb 2021 10:38:13 -0600, Luke Small wrote:
>
> > In malloc(3):
> > “If you use smaller integer types than size_t for ‘nmemb’ and ‘size’,
> then
> > multiplication in freezero() may need to be cast to size_t to avoid
> integer
> > overflow:
> > freezero(ptr, (size_t)nmemb * (size_t)size);”
> > Or maybe even: freezero(ptr, (size_t)nmemb * size);
>
> This is bad advice.  The product of two size_t values can exceed
> SIZE_MAX, at which point you would get integer overflow.  This is
> why the malloc(3) man page warns against it.  Note that on 64-bit
> platforms like amd64, size_t is already 64-bit so casting to unsigned
> long long or uint64_t is not effective.
>
> On OpenBSD, calloc(3) and reallocarray(3) check for integer overflow
> for you, which is why they are preferred over malloc(nmemb * size).
> You can examing the code yourself:
> http://cvsweb.openbsd.org/src/lib/libc/stdlib/reallocarray.c?rev=1.3
>
>  - todd
>
-- 
-Luke

Reply via email to