Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Include Page
c:INT32-C-a. Ensure that integer addition operations do not result in an overflow
c:INT32-C-a. Ensure that integer addition operations do not result in an overflow

...

Subtraction

Subtraction 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 (Unsigned)

This code may result in an unsigned integer overflow during the subtraction of the unsigned operands ui1 and ui2. If this behavior is unanticipated, it may lead to an exploitable vulnerability.

Code Block
bgColor#FFcccc

unsigned int ui1, ui2, result;

result = ui1 - ui2;

Compliant Solution (Unsigned)

This compliant solution tests the suspect unsigned subtraction operation to guarantee there is no possibility of unsigned overflow.

Code Block
bgColor#ccccff

unsigned int ui1, ui2, result;

if (ui1 < ui2){
   /* handle error condition */
}

result = ui1 - ui2;

Non-Compliant Code Example (Signed)

This code can result in a signed integer overflow during the subtraction of the signed 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 that could lead to an exploitable vulnerability.

Code Block
bgColor#FFcccc

signed int si1, si2, result;

result = si1 - si2;

Compliant Solution (Two's Complement Signed)

This compliant solution tests the suspect subtraction operation to guarantee there is no possibility of signed overflow, presuming two's complement representation.

Code Block
bgColor#ccccff

signed int si1, si2, result;

if (((si1^si2) & (((si1 ^ ((si1^si2) & (1 << (sizeof(int)*CHAR_BIT-1))))-si2)^si2)) < 0) {
  /* handle error condition */
}
result = si1 - si2;

...

Include Page
c:INT32-C-b. Ensure that integer subtraction operations do not result in an overflow
c:INT32-C-b. Ensure that integer subtraction operations do not result in an overflow

...