...
Noncompliant Code Example (Improper &
)
This noncompliant code example, derived from Flanagan \[ [Flanagan 2005|AA. References#Flanagan 05]\], has two variables, with no guarantees regarding their current values. The code must validate its data and then check whether {{ Wiki Markup array
\[i
\]
}} is nonnegative.
Code Block | ||
---|---|---|
| ||
int array[]; // may be null int i; // may be a valid index for array if (array != null & i >= 0 & i < array.length & array[i] >= 0) { // handle array } else { // handle error } |
...
This code can fail as a result of the same errors it is attempting to prevent. When {{array
}} is {{NULL
}} or when {{i
}} is not a valid index, the reference to {{array
\[i
\]
}} will cause a {{NullPointerException
}} or an {{ArrayIndexOutOfBoundsException
}} to be thrown. This happens because the {{&
}} operator fails to prevent evaluation of its right operand even when evaluation of its left operand proves that the right operand is invalid.
Compliant Solution (Use &&
)
...
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
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="37a5a0aa-ee23-438b-80a8-a2ceb5ad036a"><ac:plain-text-body><![CDATA[[[Flanagan 2005AA. References#Flanagan 05]] | 2.5.6. Boolean Operators]]></ac:plain-text-body></ac:structured-macro><ac | ||
:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e3c90b5f-a316-413e-b918-61f443e471c6"><ac:plain-text-body><![CDATA[[[JLS 2005AA. References#JLS 05]] | http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.23] | ]]></ac:plain-text-body></ac:structured-macro> | |
|
...