This is the mail archive of the
mailing list for the glibc project.
Re: [RFC][PATCH v2] Add reallocarray function.
- From: Rüdiger Sonderfeld <ruediger at c-plusplus dot de>
- To: Paul Eggert <eggert at cs dot ucla dot edu>
- Cc: libc-alpha at sourceware dot org
- Date: Wed, 21 May 2014 14:32:18 +0200
- Subject: Re: [RFC][PATCH v2] Add reallocarray function.
- Authentication-results: sourceware.org; auth=none
- References: <5379208F dot 8030000 at cs dot ucla dot edu> <1605307 dot hPebLlPzHB at descartes> <537B6155 dot 6070104 at cs dot ucla dot edu>
On Tuesday 20 May 2014 07:06:13 Paul Eggert wrote:
> First, xnrealloc's 2nd arg
> must be nonzero; this avoids a runtime check for zero so it's a bit
> faster (xnrealloc is an inline function so much of the overflow test's
> work can typically be done at compile-time).
An inline version certainly would make sense. But I don't think this could be
done for glibc.
What happens if the 2nd arg is zero in a call to `xnrealloc'? Since
`reallocarray' should primarily be about providing a safer to use API I
wouldn't want to introduce another case for undefined behavior.
And I'd like to stay compatible as much as possible with the OpenBSD
implementation (which will probably spread to other *BSDs as well).
> Second, xnrealloc's result
> is guaranteed to be non-NULL if its first arg is nonzero; this lets the
> calling code be simpler.
How can `xnrealloc' guarantee that the result will be non-NULL?
> We could alter xnrealloc to be a simple wrapper for reallocarray if
> reallocarray is available. With the current reallocarray
> implementation, though, this might not be worth the trouble, because I
> suspect xnrealloc's test for overflow is faster than reallocarray's in
> the typical case where the last argument is a constant. If you could
> fix reallocarray to use the equivalent of __builtin_umul_overflow,
> though, this objection would be removed and it would make sense for
> xnrealloc to be a wrapper for reallocarray if available.
I've changed `reallocarray' (and `calloc') to call `check_mul_overflow' for
the overflow check (v2 of the patch). This function could be replaced by a
call to `__builtin_umul_overflow' once GCC provides such an extension.
(However there would the problem of selecting the right overflow check due to
the existence of `size_t` and `INTERNAL_SIZE_T'. But that can be discussed
once the GCC extension exists.)
Is there active work done on those overflow checks in GCC? Maybe it would
make sense to provide an API like that, which if available uses the builtin.
I'm not sure if glibc would be the right place for it though. But I guess
this might be something gnulib could provide (if it hasn't something like that