Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

...

Noncompliant Code Example (Improper &)

Wiki MarkupThis 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 {{array\[i\]}} is nonnegative.

Code Block
bgColor#ffcccc
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="26f6173e-d386-4ca0-8cd9-95faa16ae0dc"><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="756a353a-d134-4ce6-90b6-49855518e7e4"><ac:plain-text-body><![CDATA[[[JLS 2005AA. References#JLS 05]]

[§15.23, "Conditional-And Operator &&"

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.23]

]]></ac:plain-text-body></ac:structured-macro>

 

§15.24, "Conditional-Or Operator"

...