Spotting ‘invisible’ null pointer dereferences with Coverity Prevent
As mentioned by Miquel in a previous article, we are using Coverity Prevent to look for possible defects in our code. Today I realised that it had spotted a possible problem that is almost invisible to the naked eye. Initially it flagged up some code that looked like this:
if (someObject.getErrorType() == SomeClass.MY_ERROR_TYPE) {
.....
}
The complaint was that getErrorType() could return a null value, so this comparison would throw an exception when the null pointer was dereferenced. That’s an easy one to fix I thought. I changed the code to look like this instead:
if (SomeClass.MY_ERROR_TYPE == someObject.getErrorType()) {
.....
}
But Coverity continued to complain about this line. It still complained that getErrorType() could return a null value and claimed that it was also being dereferenced. Both Miquel and I looked at this and decided that the tool was mistaken. But then today I suddenly realised what was going on. The left hand side of the comparison is a plain old int whereas the right hand side is an Integer. So there is an invisible call to intValue() happening to do the unboxing. Coverity picks this up, but if you just glance at the code you can’t see it. I guess this is the price you pay for auto-boxing - there is code being called that you can’t see…
UPDATE: For some reason I thought the == operator called a method on the left hand operand. It doesn’t, it merely compares the object references. So swapping the order of the operands would make no difference. I think I was fooled by being told that the left hand side was null and being dereferenced. That’s the problem you’d get with a.equals(b) where a could be null. In this case swapping the objects around would make all the difference.

(1 votes, average: 4 out of 5)
(6 votes, average: 4.83 out of 5)
