Versions Compared

Key

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

...

When converting an arithmetic or enumeration type to an enumeration type, the value is unchanged if it is in the range of enumeration values of the enumeration type. Otherwise, the value is unspecified.

Therefore, to To avoid unexpected behavior, the value being converted must be inside of the range of enumeration values. Furthermore, if it is necessary to check for out-of-range values dynamically, it must be done before the conversion.

...

This noncompliant code example is attempts to check for an out-of-bounds condition. However, it is doing so after the conversion, so the result of the conversion is unspecified and the statement may have no effect.

...

This noncompliant code may result in a truncation of the value of int_var when converted to type enum_type, resulting in execution of either case E_A or E_B instead of the default case.

...

This compliant solution checks for an out-of-bounds condition before the conversion to guarantee that there is are no unspecified values and, and thereforeconsequently, no truncation.

Code Block
bgColor#ccccff
std::cout << "case A" << std::endl;
enum enum_type {
  E_A,
  E_B
};

int int_var = 5;

if (int_var < E_A || int_var > E_B) {
  // handle error
}

switch (static_cast<enum_type>(int_var)) {
  case E_A:
    // some action A
  case E_B:
    // some action B
  default:
    // handle error
}

...

This noncompliant code may result in an infinite loop , instead of the expected behavior of looping through all enumeration values. The violation occurs at the end of the loop, when incrementing enum_var from the last valid falue value E_G produces an unspecified result.

...

GCC 4.4.3 compiles this into an infinite - loop.

Compliant Solution (For loop)

...

Unexpected behavior can lead to a buffer overflow and the execution of arbitrary code by an attacker. This is most likely if the program in one case checks the value correctly and then fails to do so later. Such a situation could allow an attacker to avoid verification of a buffer's length, etcand so on.

Automated detection should be possible for most cases, but it might not be able to know guarantee if the value is guaranteed to be in - range.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

INT36-CPP

high

probable

high

P6

L2

...