Fix issue #380: Signed integer overflow check

Instead of checking something like `x * y + z > max` where `x * y` can
overflow, check for `x > (max - z) / y` instead.
This commit is contained in:
Yixin Zhang 2016-12-09 21:31:57 -05:00
parent 79fa8b2f41
commit 1e981115c9
2 changed files with 442 additions and 920 deletions

File diff suppressed because it is too large Load diff

View file

@ -9769,19 +9769,19 @@ class basic_json
// skip if definitely not an integer
if (type != value_t::number_float)
{
// multiply last value by ten and add the new digit
auto temp = value * 10 + *curptr - '0';
auto digit = *curptr - '0';
// test for overflow
if (temp < value || temp > max)
// overflow if value * 10 + digit > max, move terms around
// to avoid overflow in intermediate values
if (value > (max - digit) / 10)
{
// overflow
type = value_t::number_float;
}
else
{
// no overflow - save it
value = temp;
// no overflow
value = value * 10 + digit;
}
}
}