BUG OF THE MONTH | data == null && throw NullReferenceException

public string ReadStringContents(int maxLength)
  if (!CanRead) return null;
  var result = StringBuilderUtilities.Pool.Get();

  if (maxLength >= 0)
    while (maxLength > 0 && !Eof)
      string data = ReadString(maxLength);
      if (data == null && data.Length > 0) break; // EOF or error.
      maxLength -= data.Length;

The V3080 warning: Possible null dereference. Consider inspecting ‘data’. PhpStream.cs 1382

The value of the data variable is checked in the loop. If the variable equals null and its Length property has a positive value, then the loop exit occurs. Clearly, it’s impossible. Moreover, we have an exception when accessing the Length variable that has the null value. Here, the access deliberately takes place when data = null.

Given the developer’s comment, I would rewrite the condition something like this:

data == null || data.Length == 0

However, it doesn’t mean that this is the correct handling option – to fix this issue, it’s better to do deep code analysis.

Please click here to see more bugs from this project.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.