V3095. The object was used before it was verified against null. Check lines: N1, N2.


The analyzer has detected a potential error that may cause access by a null reference.

The analyzer has noticed the following situation in the code: an object is being used first and only then it is checked whether this is a null reference. It means one of the following things:

1) An error occurs if the object is equal to null.

2) The program works correctly, since the object is never equal to null. The check is not necessary in this case.

Let's consider the first case. There is an error.

obj = Foo();
result = obj.Func();
if (obj == null) return -1;

If the 'obj' object is equal to null, the 'obj.Func()' expression will cause an error. The analyzer will generate a warning for this code mentioning 2 lines: the first line is the place where the object is used; the second line is the place where the object is compared to null.

This is the correct code:

obj = Foo();
if (obj == null) return -1;
result = obj.Func();

Let's consider the second case. There is no error.

Stream stream = CreateStream();
while (stream.CanRead)
{
  ....
}
if (stream != null)
  stream.Close();

This code is always correct. Stream object is never equal to null. But the analyzer does not understand this situation and generates a warning. To make it disappear, you should remove the check "if (stream != null)". It has no sense and can only confuse a programmer while reading this code.

This is the correct code:

Stream stream = CreateStream();
while (stream.CanRead)
{
  ....
}
stream.Close();

When the analyzer is wrong, you may use (apart from changing the code) a comment to suppress warnings. For example: "obj.Foo(); //-V3095".



Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++, and C#

goto PVS-Studio;
We use cookies for the analysis of events to improve our content and make user interaction more convenient. By continuing the view of our web-pages you accept the terms of using these files. You can find out more about cookie-files and privacy policy or close the notification, by clicking on the button. Learn More →
Do not show again