## SafeInt in Visual C++ 2010

The SafeInt library is a new addition to Visual C++ 2010. It allows you to safely perform arithmetic operations on integers ranging from 8-bit to 64-bit. The SafeInt library will automatically detect arithmetic overflow or divide by zero. Using the SafeInt library is pretty easy. The following piece of code uses the SafeInt library to safely calculate the addition of two 8-bit integers.

unsigned __int8 i1 = 250; unsigned __int8 i2 = 150; SafeInt<unsigned __int8> si1(i1); SafeInt<unsigned __int8> si2(i2); SafeInt<unsigned __int8> siResult = si1 + si2; cout << (int)siResult << endl;

The above example uses the default SafeIntException which will abort the application when it detects an arithmetic overflow or divide by zero. We can supply our own version of the SafeIntException as follows:

unsigned __int8 i1 = 250; unsigned __int8 i2 = 150; SafeInt<unsigned __int8, CMySafeIntException> si1(i1); SafeInt<unsigned __int8, CMySafeIntException> si2(i2); SafeInt<unsigned __int8, CMySafeIntException> siResult = si1 + si2; cout << (int)siResult << endl;

The above example will cause a CMySafeIntException, because 250+150 in 8-bit arithmetic causes an overflow. If you would not use the SafeInt library you would get the incorrect result of 144 and you would not know that something went wrong. The CMySafeIntException class is a class that I derived from SafeIntException as follows:

class CMySafeIntException : public SafeIntException { public: static void CMySafeIntException::SafeIntOnOverflow() { cout << "Caught a SafeInt Overflow exception!" << endl; } static void CMySafeIntException::SafeIntOnDivZero() { cout << "Caught a SafeInt Divide By Zero exception!" << endl; } };

Note that SafeIntException is not really a C++ exception that is thrown and catched. It’s just a class whose two functions will be called by the SafeInt library in case there is an arithmetic overflow or a divide by zero condition. The default implementation of SafeIntException will call ‘abort()’ and thus terminate the application in case an overflow or divide by zero is detected. My implementation of CMySafeIntException does not call ‘abort()’ but instead will print a message on the standard output and then just continue execution on the next line of the code.

More information about the SafeInt library can found on this MSDN page.

The Visual Studio 2010 project below is a demo application of how to use the SafeInt library.