Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This noncompliant example shows a bug in Tomcat version 4.1.24, initially discovered by Reasoning [Reasoning 2003]. The cardinality() method was designed to return the number of occurrences of object obj in collection col. One valid use of the cardinality() method is to determine how many objects in the collection are null. However, because membership in the collection is checked using the expression obj.equals(elt), a null pointer dereference is guaranteed whenever obj is null and elt is not null.

Code Block
bgColor#FFcccc
public static int cardinality(Object obj, final Collection<?> col) {
  int count = 0;
  if (col == null) {
    return count;
  }
  Iterator<?> it = col.iterator();
  while (it.hasNext()) {
    Object elt = it.next();
    if ((null == obj && null == elt) || obj.equals(elt)) {  // Null pointer dereference
      count++;
    }
  }
  return count;
}

...

The calling method, testString(), guarantees that isProperName() is always called with a valid string reference.  As As a result, the class conforms with this rule even though a public isProperName() method would not. Guarantees of this sort can be used to eliminate null pointer dereferences.

...

Risk Assessment

Dereferencing a null pointer can lead to a denial of service. In multithreaded programs, null pointer dereferences can violate cache coherency policies and can cause resource leaks.

...