add fcn product_overflow()

This commit is contained in:
Jim Monte 2020-04-25 19:54:28 +02:00 committed by Holger Vogt
parent a2b5d009db
commit 654c9767d6
1 changed files with 41 additions and 3 deletions

View File

@ -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 */