...
Code Block | ||
---|---|---|
| ||
int array[]; // may be null int i; // may be a valid index for array if (data array!= null) { if (i >= 0 & i < dataarray.length) { if (dataarray[i] != -1) { // use array } else { // handle error } } else { // handle error } } else { // handle error } |
Nevertheless, this solution is preferable if the error-handling routines code for each potential condition failure were different.
...
The problem with this code is that when the first condition in the while
loop fails, the second condition is not executed. That is, once i1
has reached array1.length
, the loop could will terminate after i1
is executedincremented. Consequently, the apparent range over array1
is larger than the apparent range over array2
, causing the final assertion to fail.
...
Code Block | ||
---|---|---|
| ||
while (++i1 < array1.length & // not && ++i2 < array2.length && array1[i1] == array2[i2]) |
Compliant Solution (Nested if
Statements)
This compliant solution uses multiple if
statements to achieve the proper effect. Although correct, it is more verbose.
Code Block | ||
---|---|---|
| ||
while (true) {
if (++i1 >= array1.length) break;
if (++i2 >= array2.length) break;
if (array1[i1] != array2[i2]) break;
// rest of loop
}
|
...
Applicability
Failure to understand the behavior of the bitwise and conditional operators can cause unintended program behavior.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP54-JG | low | unlikely | medium | P2 | L3 |
Related Guidelines
CERT C Secure Coding Standard: EXP02-C. Be aware of the short-circuit behavior of the logical AND and OR operators
CERT C++ Secure Coding Standard: EXP02-CPP. Be aware of the short-circuit behavior of the logical AND and OR operators
Bibliography
2.5.6. Boolean Operators | |
|
...