This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [PATCH] Add reallocarray function.


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."


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]