1

Why do FindBugs raises me the following warning: Possible null pointer dereference.

current = myService.getCategoryParent(current);
if (current != null) { // The warning appears here

I don't understand how testing a variable against null could dereference it.

4
  • @MichaelBorgwardt It's a custom Category class Apr 25, 2012 at 9:00
  • Is current used at all after/outside of this if-statement? Apr 25, 2012 at 9:00
  • @BeRecursive: It's used on the line above. Apr 25, 2012 at 9:03
  • @T.J.Crowder ah yes that would make sense Apr 25, 2012 at 9:10

1 Answer 1

2

I suspect the error/warning is actually on the line above the line you've indicated.

//                   here ------------v
current = myService.getCategoryParent(current);
if (current != null) {
4
  • Sonar reports the warning on the second line, but I added the line above just to be sure because I also have a doubt... If that was the case, then what would the warning be about? Apr 25, 2012 at 9:01
  • @Matthieu: Presumably it's worried that getCategoryParent is going to dereference the argument passed in? Does getCategoryParent have a !null check? Apr 25, 2012 at 9:02
  • Yes there is a !=null check. However getCategoryParent can return null, may that be it? Apr 25, 2012 at 9:05
  • @Matthieu: getCategoryParent returning null isn't a problem, because you've got the null check just after you call it. As an experiment, I recommend putting 10 System.out.println("foo"); lines between the two lines you've quoted, and running FindBugs again, just in case there's an oboe (off-by-one error) in its line number reporting. Just to narrow down which line it's actually warning about. Apr 25, 2012 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.