Image Reference: https://wizardzines.com/comics/integer-overflow/ Integer overflow is especially problematic for signed integer overflow, which is undefined behavior.
uint x = UINT_MAX + 1; -> overflow + round to 0
int x = INT_MAX + 1; -> overflow + undefined behavior
There's no way to detect int overflows directly in C
But there is hardware support in the CPU, so maybe we can mix C and assembly?
after arithmetic instructions [add, sub, mul]
CPU sets flag registers
- OF = Overflow flag (signed overflow)
- CF = Carry flag (unsigned overflow)
these flags are available in assembly, but are not directly exposed in C
Assembly instructions:
- jo (jump if OF=1)
- seto (set if OF=1)
- jno (jump if OF=0)
- jc (jump if CF=1)
GCC and Clang provide compiler intrinsics that perform arithmetic while reporting whether an overflow occurred
bool __builtin_add_overflow(type a, type b, type *result); [/sub/mul]
This is a recreational project.
#include <ioverflow.h>
int8 a=250;
if (!would_overflow(a,'+',5)) {
// ..
}Supports '+', '-' and '*'
typedef unsigned char int8;
typedef unsigned short int int16;
typedef unsigned int int32;
typedef signed char sint8;
typedef signed short int sint16;
typedef signed int sint32;
Requires nasm and a 32-bit capable gcc (gcc-multilib on most distros):
sudo apt install nasm gcc-multilib
makeThis produces libioverflow.a.
Install system-wide with:
sudo make installwhich drops libioverflow.a into /usr/local/lib and ioverflow.h into /usr/local/include.