Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of Possible null pointer dereference in findbug?

I am using Sonar and I have got this kind of violation from it for a peace of my code:

 Correctness - Possible null pointer dereference  

Has anyone know about this rule in findbugs? I searched a lot but I can not find a good sample code (in Java) which describe this rule, unfortunately findbugs site did not have any sample code or good description about this rule.

Why does this violation appear?

like image 777
Saeed Zarinfam Avatar asked Sep 03 '12 05:09

Saeed Zarinfam


4 Answers

a sample code is something like this.

String s = null ;
if (today is monday){
    s = "Monday" ;
else if (today is tuesday){
    s = "Tuesday" ;
}
System.out.println(s.length()); //Will throw a null pointer if today is not monday or tuesday.
like image 124
Balaji Natesan Avatar answered Oct 17 '22 22:10

Balaji Natesan


It says here

NP: Possible null pointer dereference (NP_NULL_ON_SOME_PATH)

There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs.

If you would have posted some code it would be easier to answer.

EDIT I don't see a lot of documentation but here is one example! Hope this helps!

like image 24
Bharat Sinha Avatar answered Oct 17 '22 22:10

Bharat Sinha


Okay

This is two simple Examples : First one gives a : Possible null pointer dereference

1. Error
     ArrayList a = null;
     a.add(j, PointSet.get(j));
     // now i'm trying to add to the ArrayList 
     // because i'm giving it null it gives me the "Possible null pointer dereference"

2. No Error
     ArrayList a = new ArrayList<>();
     a.add(j, PointSet.get(j));
     // adding elements to the ArrayList
     // no problem

Simple ?

like image 3
ucefkh Avatar answered Oct 17 '22 22:10

ucefkh


I got this issue with the following piece of code:-

BufferedReader br = null;
    String queryTemplate = null;
    try {
        br = new BufferedReader(new FileReader(queryFile));
        queryTemplate = br.readLine();
    } catch (FileNotFoundException e) {
      //  throw exception
    } catch (IOException e) {
       // throw exception
    } finally {
        br.close();
    }

Here, the br BufferedReader can be null in br.close(). However it can only be null if new BufferedReader() fails, in which case we are throwing the relevant exceptions.

This is thus a false warning. Findbugs docs mention the same:-

   This may lead to a NullPointerException when the code is executed.  
   Note that because FindBugs currently does not prune infeasible 
   exception paths, this may be a false warning.
like image 1
Sanchay Avatar answered Oct 17 '22 23:10

Sanchay