This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: Why was the reallocarray function not added to glibc?
On 10/04/17 16:24, Zack Weinberg wrote:
> On Mon, Apr 10, 2017 at 6:15 AM, Szabolcs Nagy <szabolcs.nagy@arm.com> wrote:
>>
>> the idiomatic unsigned mul overflow check is
>>
>> if (b && -1/b < a)
>> return 0;
>> c = a*b;
>
> I've never seen this construct before; it is not obvious to me why it
> checks for unsigned mul overflow. It would need, at the very least,
> an explanation in comments. Also, this...
>
> #include <stdlib.h>
>
> void *reallocarray(void *ptr, size_t size, size_t nmemb)
> {
> if (!size || !nmemb) {
> free(ptr);
> return 0;
> }
> if (-1/nmemb < size) {
> return 0;
> }
> return realloc(ptr, size * nmemb);
> }
>
> ... generates code with a divide instruction in it, using either gcc
> 6.3.0 or clang 3.8.1, so I do not think we can use it yet.
gcc-7 gets it right though (single mul)
and this code is portable with no hacks.