V503. This is a nonsensical comparison: pointer < 0

19.11.2010

The analyzer found a code fragment that has a nonsensical comparison. It is most probable that this code has a logic error. Here is an example:

class MyClass {
public:
  CObj *Find(const char *name);
  ...
} Storage;

if (Storage.Find("foo") < 0)
  ObjectNotFound();

It seems almost incredible that such a code can exist in a program. However, the reason for its appearance might be quite simple. Suppose we have the following code in our program:

class MyClass {
public:
  // If the object is not found, the function
  // Find() returns -1.
  ptrdiff_t Find(const char *name);
  CObj *Get(ptrdiff_t  index);
  ...
} Storage;
...
ptrdiff_t index = Storage.Find("ZZ");
if (index >= 0)
  Foo(Storage.Get(index));
...
if (Storage.Find("foo") < 0)
  ObjectNotFound();

This is correct yet not very smart code. During the refactoring process, the MyClass class may be rewritten in the following way:

class MyClass {
public:
  CObj *Find(const char *name);
  ...
} Storage;

After this modernization of the class, you should fix all the places in the program which use the Find() function. You cannot miss the first code fragment since it will not be compiled, so it will be certainly fixed:

CObj *obj = Storage.Find("ZZ");
if (obj != nullptr)
  Foo(obj);

The second code fragment is compiled well and you might miss it easily and therefore make the error we are discussing:

if (Storage.Find("foo") < 0)
  ObjectNotFound();
You can look at examples of errors from real projects which were detected by this diagnostic message.