On Thu, Mar 26, 2015 at 02:32:34AM +0900, Masatake YAMATO wrote:
[...]
> +/*
> + * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
> + * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
> + */
> +#define MUL_NO_OVERFLOW      ((size_t)1 << (sizeof(size_t) * 4))
> +
> +static void *
> +reallocarray(void *optr, size_t nmemb, size_t size)
>  {
> -     void *r= realloc(ptr, size);
> +     if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
> +         nmemb > 0 && SIZE_MAX / nmemb < size) {
> +             errno = ENOMEM;
> +             return NULL;
> +     }
> +     return realloc(optr, size * nmemb);
> +}
> +
> +void *
> +xreallocarray(void *optr, size_t nmemb, size_t size)
> +{
> +     void *r;
> +
> +     r = reallocarray(optr, nmemb, size);
>       if (!r)
>               die_out_of_memory();
>       return r;

I don't quite like this implementation.
As the next action in case of integer overflow is die_out_of_memory,
there is no need to optimize for that case.

I think it should rather be something like this:

size_t bytes = nmemb * size;
if ((nmemb | size) >= MUL_NO_OVERFLOW &&
    size && bytes / size != nmemb) {
        die_out_of_memory();
}


-- 
ldv

Attachment: pgpov3I92Aynm.pgp
Description: PGP signature

------------------------------------------------------------------------------
Dive into the World of Parallel Programming The Go Parallel Website, sponsored
by Intel and developed in partnership with Slashdot Media, is your hub for all
things parallel software development, from weekly thought leadership blogs to
news, videos, case studies, tutorials and more. Take a look and join the 
conversation now. http://goparallel.sourceforge.net/
_______________________________________________
Strace-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/strace-devel

Reply via email to