From 654c9767d68358e9cb86a46c949f0a728e25e8f2 Mon Sep 17 00:00:00 2001 From: Jim Monte Date: Sat, 25 Apr 2020 19:54:28 +0200 Subject: [PATCH] add fcn product_overflow() --- src/misc/alloc.c | 44 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/src/misc/alloc.c b/src/misc/alloc.c index d870999e2..2d021e091 100644 --- a/src/misc/alloc.c +++ b/src/misc/alloc.c @@ -47,7 +47,6 @@ extern mutexType allocMutex; */ /* New implementation of tmalloc, it uses calloc and does not call memset() */ - void * tmalloc(size_t num) { @@ -148,6 +147,45 @@ txfree(const void *ptr) #elif defined SHARED_MODULE mutex_unlock(&allocMutex); #endif -} +} /* end of function txfree */ -#endif + +/* This function returns the product of a and b if it does not overflow. + * + * Return codes + * 0: No overflow + * 1: overflow + */ +static inline int product_overflow(size_t a, size_t b, size_t *p_n) +{ + /* Some overflow conditions: + * a == SIZE_MAX and b > 1 + * a > 1 and b == SIZE_MAX + * a * b < a + * a * b < b + */ + if ((a == SIZE_MAX && b > 1) || (a > 1 && b == SIZE_MAX)) { + return +1; + } + + const size_t n = a * b; + if (n < a || n < b) { + return +1; + } + + *p_n = n; + return 0; +} /* end of function product_overflow */ + + +/* Print error related to allocating a product that cannot fit in a + * size_t and exit. This function does not return. */ +static void overflow_error(size_t num, size_t size) +{ + (void) fprintf(stderr, "Cannot allocate %zu X %zu bytes: " + "Product exceeds largest size_t = %zu.\n", + num, size, SIZE_MAX); + controlled_exit(EXIT_FAILURE); +} /* end of function overflow_error */ + +#endif /* #ifndef HAVE_LIBGC */