...
Code Block | ||
---|---|---|
| ||
enum et1enum_type { E_A, E_B }; int i1int_var = -1; et1 e1enum_type enum_var = static_cast<enum_cast<et1>type>(i1int_var); if (e1enum_var < E_A) { /*/ handle error condition */ } |
Compliant
...
Solution (Bounds checking)
This compliant solution checks for an out-of-bounds condition before the conversion to guarantee there is no unspecified result.
Code Block | ||
---|---|---|
| ||
enum et1enum_type { E_A, E_B }; int i1int_var = -1; if (i1int_var < E_A || i1int_var > E_B) { /*/ handle error condition */ } et1 e1enum_type enum_var = static_cast<et1>(i1cast<enum_type>(int_var); |
Noncompliant Code Example (Switch
...
statement)
This noncompliant code may result in a truncation of the value of i1
int_var
when converted to type enum_type
et1
resulting in execution of either case E_A
or E_B
instead of the default case.
Code Block | ||
---|---|---|
| ||
enum et1enum_type { E_A, E_B }; int i1int_var = 5; switch (static_cast<enum_cast<et1>type>(i1int_var)) { case E_A: /*/ some action A */ case E_B: //* some action B */ default: /*/ handle error condition */ } |
Compliant
...
Solution (Switch
...
statement)
This compliant solution checks for an out-of-bounds condition before the conversion to guarantee that there is no unspecified values, and therefore, no truncation.
Code Block | ||
---|---|---|
| ||
std::cout << "case A" << std::endl; enum et1enum_type { E_A, E_B }; int i1int_var = 5; if (i1int_var < E_A || i1int_var > E_B) { //* handle error condition */ } switch (static_cast<enum_cast<et1>type>(i1int_var)) { case E_A: //* some action A */ case E_B: /*/ some action B */ default: /*/ handle error condition */ } |
Noncompliant Code Example (For
...
loop)
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 e1 = static_cast<e1>(E_G+1), which is out-of-rangeincrementing enum_var
from the last valid falue E_G
produces an unspecified result.
Code Block | ||
---|---|---|
| ||
enum et1enum_type { E_A = 1, E_B, E_C, E_D, E_E, E_F, E_G }; for(et1 e1enum_type enum_var = E_A; e1enum_var <= E_G; e1enum_var = static_cast<enum_cast<e1>var>(e1enum_var+1)) { //* some action */ } |
Implementation Details
GCC 4.4.3 compiles this into an infinite-loop.
Compliant
...
Solution (For
...
loop)
This compliant solution prevents any out-of-bounds arithmetic on the enumeration type.
Code Block | ||
---|---|---|
| ||
enum et1enum_type { E_A = 1, E_B, E_C, E_D, E_E, E_F, E_G }; for(int i = E_A; i <= E_G; i = i+1) { //* some action */ } |
Risk Assessment
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, etc.
...