[PATCH 2/2] Replace xrealloc with xreallocarray
Dmitry V. Levin
ldv at altlinux.org
Thu Mar 26 17:58:31 UTC 2015
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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.strace.io/pipermail/strace-devel/attachments/20150326/7484b317/attachment.bin>
More information about the Strace-devel
mailing list