Tutorial and Motivating Examples
Arithmetic operations can yield incorrect results. When some operation results in a result which exceeds the capacity of a data variable to hold it, the result is undefined. This is called "overflow". Since word size can differ between machines, code which produces correct results in one set of circumstances may fail when re-compiled on a machine with different hardware. When this occurs, Most C++ compilers will continue to execute with no indication that the results are wrong. It is the programmer's responsibility to ensure such undefined behavior is avoided. This program demonstrates this problem. The solution is to replace instances of char type with safe<char> type.
Undetected overflow A variation of the above is when a value is incremented/decremented beyond it's domain. This is a common problem with for loops.
Undetected underflow A variation of the above is when a value is incremented/decremented beyond it's domain. This is a common problem with for loops.
Implicit conversions change data values A simple assignment or arithmetic expression will generally convert all the terms to the same type. Sometimes this can silently change values. For example, when a signed data variable contains a negative type, assigning to a unsigned type will be permitted by any C/C++ compiler but will be treated as large unsigned value. Most modern compilers will emit a compile time warning when this conversion is performed. The user may then decide to change some data types or apply a static_cast. This is less than satisfactory for two reasons: It may be unwieldy to change all the types to signed or unsigned. Littering one's program with static_cast makes it more difficult to read. We may believe that our signed type will never contain a negative value. If we use a static_cast to suppress the warning, we'll fail to detect a program error when it is committed. This is aways a risk with casts. This solution is the same as the above, Just replace instances of the int with safe<int>.
Array index value can exceed array limits Using an intrinsic C++ array, it's very easy to exceed array limits. This can fail to be detected when it occurs and create bugs which are hard to find. There are several ways to address this, but one of the simplest would be to use safe_unsigned_range;
Checking of initialization values can be easily overlooked It's way too easy to overlook the checking of parameters received from outside the current program.Without safe integer, one will have to insert new code every time an integer variable is retrieved. This is a tedious and error prone procedure.