Null pointers should not be dereferenced

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Null pointers should not be dereferenced相关的知识,希望对你有一定的参考价值。

A reference to null should never be dereferenced/accessed. Doing so will cause a NullPointerException to be thrown. At best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or it could allow an attacker to bypass security measures.

Note that when they are present, this rule takes advantage of @CheckForNull and @Nonnull annotations defined in JSR-305 to understand which values are and are not nullable.

@Nullable denotes that, under some unspecified circumstances, the value might be null. To keep false positives low, this annotation is ignored. Whether an explicit test is required or not is left to the developer‘s discretion.

Noncompliant Code Example

Here are some examples of null pointer dereferences detected by this rule:

@CheckForNull
String getName(){...}

public boolean isNameEmpty() {
  return getName().length() == 0; // Noncompliant; the result of getName() could be null, but isn‘t null-checked
}
Connection conn = null;
Statement stmt = null;
try{
  conn = DriverManager.getConnection(DB_URL,USER,PASS);
  stmt = conn.createStatement();
  // ...

}catch(Exception e){
  e.printStackTrace();
}finally{
  stmt.close();   // Noncompliant; stmt could be null if an exception was thrown in the try{} block
  conn.close();  // Noncompliant; conn could be null if an exception was thrown
}
private void merge(@Nonnull Color firstColor, @Nonnull Color secondColor){...}

public  void append(@CheckForNull Color color) {
    merge(currentColor, color);  // Noncompliant; color should be null-checked because merge(...) doesn‘t accept nullable parameters
}
void paint(Color color) {
  if(color == null) {
    System.out.println("Unable to apply color " + color.toString());  // Noncompliant; NullPointerException will be thrown
    return;
  }
  ...
}

以上是关于Null pointers should not be dereferenced的主要内容,如果未能解决你的问题,请参考以下文章

解决EnforceNotMet: grad_op_maker_ should not be null Operator GradOpMaker has not been registered. at(

Android开发中微信分享失败之checkArgs fail, thumbData should not be null or exceed 128kb

Android开发中微信分享失败之checkArgs fail, thumbData should not be null or exceed 128kb

git-lfs文件坏掉的问题 Encountered 2 file(s) that should have been pointers, but weren't

String literals should not be duplicated

- cinfiguration.resolve.extensitions should not be enpty.