This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
Re: [PATCH] Add reallocarray function.
- From: Andreas Schwab <schwab at suse dot de>
- To: Dennis Wölfing <denniswoelfing at gmx dot de>
- Cc: libc-alpha at sourceware dot org
- Date: Mon, 10 Apr 2017 18:03:18 +0200
- Subject: Re: [PATCH] Add reallocarray function.
- Authentication-results: sourceware.org; auth=none
- References: <20170410150053.10208-1-denniswoelfing@gmx.de>
On Apr 10 2017, Dennis Wölfing <denniswoelfing@gmx.de> wrote:
> diff --git a/malloc/malloc.c b/malloc/malloc.c
> index 4c40e2ea19..ca22e53f63 100644
> --- a/malloc/malloc.c
> +++ b/malloc/malloc.c
> @@ -2950,6 +2950,39 @@ __libc_free (void *mem)
> }
> libc_hidden_def (__libc_free)
>
> +static inline bool
> +check_mul_overflow(size_t l, size_t r, INTERNAL_SIZE_T *result)
> +{
> +#if __GNUC__ >= 5
> + return __builtin_mul_overflow(l, r, result);
> +#else
> + /* size_t is unsigned so the behavior on overflow is defined. */
> + *result = l * r;
> +# define HALF_INTERNAL_SIZE_T \
> + (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
> + if (__glibc_unlikely ((l | r) >= HALF_INTERNAL_SIZE_T))
> + {
> + if (r != 0 && *result / r != l)
> + return true;
> + }
> + return false;
> +# undef HALF_INTERNAL_SIZE_T
> +#endif
> +}
> +
> +void *
> +__libc_reallocarray(void *optr, size_t nmemb, size_t elem_size)
> +{
> + INTERNAL_SIZE_T bytes;
> + if (check_mul_overflow(nmemb, elem_size, &bytes))
> + {
> + __set_errno (ENOMEM);
> + return 0;
> + }
> + else
> + return __libc_realloc (optr, bytes);
> +}
> +
Style: please put a space before paren on function calls.
Andreas.
--
Andreas Schwab, SUSE Labs, schwab@suse.de
GPG Key fingerprint = 0196 BAD8 1CE9 1970 F4BE 1748 E4D4 88E3 0EEA B9D7
"And now for something completely different."