...
This noncompliant code example attempts to check whether a given value is within the range of acceptable enumeration values. However, it is doing so after casting to the enumeration type, which may not be able to represent the given integer value. On a two's complement system, the valid range of values that can be represented by enum_type
are [0..3], so if a value outside of that range were passed to f()
, the cast to enum_type
would result in an unspecified value, and using that value within the if
statement results in unspecified behavior.
Code Block | ||||
---|---|---|---|---|
| ||||
enum enum_type { E_A, E_B, E_C }; void f(int int_var) { enum_type enum_var = static_cast<enum_type>(int_var); if (enum_var < E_A || enum_var > E_C) { // Handle error } } |
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT50-CPP | Medium | Unlikely | Medium | P4 | L3 |
Automated Detection
Automated detection should be possible for most cases, but it might not be able to guarantee that the value is in range.
...