...
This compliant solution checks for an out-of-bounds condition before the conversion to guarantee there is no unspecified values, and therefore, no truncation.
Code Block | ||
---|---|---|
| ||
std::cout << "case A" << std::endl;
enum et1 {
E_A,
E_B
};
int i1 = 5;
if (i1 < E_A || i1 > E_B) {
/* error condition */
}
switch(static_cast<et1>(i1)) {
case E_A:
/* some action A */
case E_B:
/* some action B */
}
|
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.
Code Block | ||
---|---|---|
| ||
enum et1 {
E_A = 1,
E_B,
E_C,
E_D,
E_E,
E_F,
E_G
};
for(et1 e1 = E_A; e1 <= E_G; e1 = static_cast<e1>(e1+1)) {
/* some action */
}
|
GCC 4.4.3 compiles this into an infinite-loop.
Compliant Code Example (For-loop)
Code Block | ||
---|---|---|
| ||
enum et1 {
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.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT36-CPP | high | probable | high | P6 | L2 |
References
Wiki Markup |
---|
\[[Becker 09|AA. References#Becker 09]\] Section 7.2, "Enumeration declarations" |