Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Null Dereference when setting a field to null - Fortify

Tags:

java

fortify

Fortify is complaining about a Null Dereference when I set a field to null:

String sortName = null;
if (lastName != null && lastName.length() > 0) {
   sortName = lastName;
}
sortOptions.setSortField(sortName);  <--  Fortify Null Dereference

Fortify's analysis trace says:

Assigned null: sortName
Branch taken: if (lastName != null && lastName.length() > 0)
Dereferenced: sortName

I could try:

if (sortName == null)
   sortOptions.setSortField(null);
else
   sortOptions.setSortField(sortName);

But that seems really silly. Anyone have experience with this one? I'd prefer to get rid of the finding vs. just write it off.

like image 937
lovebeer84 Avatar asked May 11 '26 11:05

lovebeer84


1 Answers

What fortify do not like is the fact that you initialize the variable with null first, without condition, and then change it.

this should work:

String sortName;
if (lastName != null && lastName.length() > 0) {
   sortName = lastName;
} else {
   sortName = null;
}
sortOptions.setSortField(sortName);

(Or use the ternary operator if you prefer)

This way you initialize sortName only once, and explicitely show that a null value is the right one in some cases, and not that you forgot some cases, leading to a var staying null while it is unexpected.

The Null dereference error was on the line of code sortName = lastName; not the call of the setter : fortify do not want you to conditionnally change the value of a variable that was set to null without doing so in all the branches.

like image 134
Thierry Avatar answered May 14 '26 03:05

Thierry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!