Pages

January 21, 2014

Determining Integer Overflow

This topic was running through my mind and I was wondering what the easiest way would be to detect overflow and underflow of integers. I searched on the internet and found some answers but all were not quite simple. Then it dawned on me that the CPU has an Overflow flag as part of the EFLAGS register! Consulted the Intel SW Developers manual and found that I was right. There are instructions that test this register - the JO (Jump if overflow) for signed integers and JC (Jump if carry) for unsigned integers. So, we perform an addition and then immediately check the status of the flags using the JO/JC instructions. The branch instruction targets can then return the correct value if this logic is enclosed within a function that tests this overflow condition. I have added the two small functions that test for overflow in INT and UINT to my CHelpLib git repository. I have included one of the functions below. Given two integers, this function returns TRUE if an addition causes overflow. It basically uses assembly instructions to perform the addition and then uses jo instruction to jump to the correct location that returns the TRUE or FALSE value.

BOOL Chl_fIsOverflowINT(int a, int b)
{
    __asm
    {
        mov eax, dword ptr [a]
        mov ecx, dword ptr [b]
        add eax, ecx
        jo ret_overflow
    }

    return FALSE;
    
ret_overflow:
    return TRUE;
}