mirror of
https://github.com/justinethier/cyclone.git
synced 2025-05-24 20:45:06 +02:00
Issue #276 - Improve overflow detection for multiplication
This commit is contained in:
parent
b2326b89f4
commit
b41971e187
1 changed files with 5 additions and 8 deletions
13
runtime.c
13
runtime.c
|
@ -3050,17 +3050,14 @@ static int Cyc_checked_sub(int x, int y, int *result)
|
||||||
return ((((*result ^ x) & ~(*result ^ y)) >> 30) != 0);
|
return ((((*result ^ x) & ~(*result ^ y)) >> 30) != 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Code from http://stackoverflow.com/q/1815367/101258
|
|
||||||
static int Cyc_checked_mul(int x, int y, int *result)
|
static int Cyc_checked_mul(int x, int y, int *result)
|
||||||
{
|
{
|
||||||
// *result = x * y;
|
// Avoid undefined behavior by detecting overflow prior to multiplication
|
||||||
// return (*result != 0 && (*result)/x != y) || // Overflow
|
// Based on code from Hacker's Delight and CHICKEN scheme
|
||||||
// (*result > CYC_FIXNUM_MAX) ||
|
|
||||||
// (*result < CYC_FIXNUM_MIN);
|
|
||||||
uint xu, yu, c;
|
uint xu, yu, c;
|
||||||
c = 1UL<<31UL;
|
c = (1UL<<30UL) - 1;
|
||||||
xu = x < 0 ? -1 : x;
|
xu = x < 0 ? -x : x;
|
||||||
yu = y < 0 ? -1 : y;
|
yu = y < 0 ? -y : y;
|
||||||
|
|
||||||
if (yu != 0 && xu > (c / yu)) return 1; // Overflow
|
if (yu != 0 && xu > (c / yu)) return 1; // Overflow
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue