V698. strcmp()-like functions can return not only the values -1, 0 and 1, but any values.


The analyzer has detected a comparison of the result of strcmp() or similar function to 1 or -1. The C/C++ language specification, however, says that the strcmp() function can return any positive or negative value when strings are not equal – not only 1 or -1.

Depending on the implementation, the strcmp() function can return the following values when strings are not equal:

  • -1 or any negative number if the first string is less than the second in the lexicographical order;
  • 1 or any positive number if the first string is larger than the second.

Whether constructs like strcmp() == 1 will work right depends on libraries, the compiler and its settings, the operating system and its bitness, and so on; in this case you should always write strcmp() > 0.

For example, below is a fragment of incorrect code:

std::vector<char *> vec;
....
std::sort(vec.begin(), vec.end(), [](
    const char * a, const char * b)
  {
    return strcmp(a, b) == 1;
  });

When you change over to a different compiler, target operating system or application bitness, the code may start working improperly.

The fixed code:

std::vector<char *> vec;
....
std::sort(vec.begin(), vec.end(), [](
    const char * a, const char * b)
  {
    return strcmp(a, b) > 0;
  });

The analyzer also considers code incorrect when it compares results of two strcmp() functions. Such code is very rare but always needs examining.

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-253.

You can look at examples of errors detected by the V698 diagnostic.


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