int32_t result = registers[rs] + registers[rt];
if (((registers[rs] > 0) && (registers[rt] > 0) && (result < 0)) ||
((registers[rs] < 0) && (registers[rt] < 0) && (result > 0))) {
fprintf(stderr, "arithmetic overflow\n");
} else {
registers[rd] = result;
}
Just a simple add and detect the overflow, if registers[rs]
is 2147483647 and registers[rt]
is 1, registers[rd]
will have a result -2147483648. But if I add a printf("%d\\n", result)
after declaring the variable result with same value in rs
and rt
, it will display arithmetic overflow
when registers[rs]
is 2147483647 and registers[rt]
is 1, it should output the arithmetic overflow
int32_t result = registers[rs] + registers[rt];
When signed integer overflow occurs it invokes UB(Undefined Bahaviour).
You need to check before you add those integers.
bool willOverflow(int32_t a, int32_t b)
{
bool overflow = false;
if (a > 0 && b > 0 && (a > INT32_MAX - b))
{
overflow = true;
}
else if (a < 0 && b < 0 && (a < INT32_MIN - b))
{
overflow = true;
}
return overflow;
}
if (willOverflow(registers[rs], registers[rt]))
{
fprintf(stderr, "arithmetic overflow\n");
}
else
{
registers[rd] = registers[rs] + registers[rt];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With