...
Code Block |
---|
unsigned int sum; unsigned int ui1 = UINT_MAX; unsigned int ui2 = 1; if (~ui1 < ui2){ error_handler("Overflow Error", NULL, EOVERFLOW); } sum = ui1 + ui2; |
Subtraction
Subtraction in C is between two operands of arithmetic type, two pointers to qualified or unqualified versions of compatible object types, or between a pointer to an object type and an integer type. (Decrementing is equivalent to subtracting one.)
Non-compliant Code Example
The following code will result in a signed integer overflow during the subtraction of the unsigned operands si1 and si2. If this behavior is unanticipated, the resulting value may be used to allocate insufficient memory for a subsequent operation or in some other manner which could lead to an exploitable vulnerability.
Code Block |
---|
signed int result;
signed int si1 = INT_MAX;
signed int si2 = -1;
result = si1 - si2;
|
Compliant Solution
The following compliant solution tests the suspect subtraction operation to guarantee there is no possibility of signed overflow. In this particular case, an overflow condition is present and the error_handler()
method is invoked.
Code Block |
---|
signed int result;
signed int si1 = INT_MAX;
signed int si2 = -1;
if ( ((lhs^rhs)&((lhs-rhs)^lhs)) >> (sizeof(int)*CHAR_BIT-1) ){
error_handler("OVERFLOW ERROR", NULL, EOVERFLOW);
}
result = si1 - si2;
|