Versions Compared

Key

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

...

Anchor
Unary Negation
Unary Negation

...

Unary Negation

The unary negation operator takes an operand of arithmetic type. Overflow can occur during twos-complement unary negation when the operand is equal to the minimum (negative) value for the signed integer type.

Non-Compliant Code Example

This non-compliant code example can result in a signed integer overflow during the unary negation of the signed operand si1. 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, result;

result = -si1;

Compliant Solution

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

Code Block
bgColorccccff

signed int si1, result;

if (si1 == INT_MIN) {
  /* handle error condition */
}
result = -si1;

Anchor
Left Shift Operator
Left Shift Operator

Left Shift Operator

The left shift operator is between two operands of integer type.

Non-Compliant Code Example (Unsigned)

This code can result in an unsigned overflow during the shift operation of the unsigned operands ui1 and ui2. 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

unsigned int ui1, ui2, uresult;

uresult = ui1 << ui2;

Compliant Solution (Unsigned)

This compliant solution tests the suspect shift operation to guarantee there is no possibility of unsigned overflow. This solution must also be compliant with INT36-C. Do not shift a negative number of bits or more bits than exist in the operand.

Code Block
bgColor#ccccff

unsigned int ui1, ui2, uresult;

if ( (ui2 >= sizeof(unsigned int)*CHAR_BIT) || (ui1 > (UINT_MAX  >> ui2))) ) {
  /* handle error condition */
}
else {
  uresult = ui1 << ui2;
}

...

Exceptions

INT32-EX1. Unsigned integers can exhibit modulo behavior only when this behavior is necessary for the proper execution of the program. It is recommended that the variable declaration be clearly commented as supporting modulo behavior and that each operation on that integer also be clearly commented as supporting modulo behavior.

...