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?
Dennis Wölfing wrote:
the INT_MULTIPLY_OVERFLOW implementation uses compiler
builtins only with GCC 7 or higher because it uses
__builtin_mul_overflow_p.
Ah, you're right, I'd forgotten that because INT_MULTIPLY_OVERFLOW is also
intended for use in constant expressions, it cannot use __builtin_mul_overflow.
So I guess it's better to simply use
__builtin_mul_overflow when __GNUC__ >= 5, and use the current
implementation otherwise.
That would work, yes. Using INT_MULTIPLY_OVERFLOW instead of the current
implementation would perhaps be better, if "better" is understood to mean
simpler and/or less runtime code.
One other thing. Lots of C programs break if they allocate objects containing
more than PTRDIFF_MAX bytes, since pointer subtraction stops working. Shouldn't
realloc_array prevent this problem too? Something like this:
static inline bool
check_mul_overflow (size_t a, size_t b, size_t *result)
{
#if __GNUC_PREREQ (5, 0)
bool v = __builtin_mul_overflow (a, b, result);
#else
*result = a * b;
bool v = INT_MULTIPLY_OVERFLOW (a, b);
#endif
return v | PTRDIFF_MAX < *result;
}
Of course a similar check should be added to malloc etc., but one step at a time.