V806. Decreased performance. The expression of strlen(MyStr.c_str()) kind can be rewritten as MyStr.length().

Analyzer found a construct which potentially can be optimized. The length of a string located in the container is calculated by using the strlen() function or by function similar to it. This operation is excessive, as the container possesses a special function for string length calculation.

Let's review this example:

static UINT GetSize(const std::string& rStr)
  return (strlen(rStr.c_str()) + 1 );

This code belongs to a real-life application. Usually such funny code fragments are created during careless refactoring. This code is slow and, even more, quite possibly even unnecessary. When it is required you can just write "string::length() + 1".

Nevertheless, if you are willing to create a special function for calculating the size of a null-terminated string, it should appear as follows:

inline size_t GetSize(const std::string& rStr)
  return rStr.length() + 1;


One should remember that "strlen(MyString.c_str())" and "MyString.length()" operations will not always generate the same result. The differences will appear in case a string contains null characters besides the terminal one. However such situations can be viewed as a very bad design practice, so the V806 warning message is a great reason to consider the possibility of refactoring. Even if the developer who created this code understands its' operational principles quite well, nevertheless it will be hard to understand this code for his colleagues. They will wonder about the purpose of such a style and could potentially replace the call to "strlen()" function with "length()", thus creating a bug in the program. So one should not be lazy and should replace it with such a code in which operational principles are clear and intelligible to even an outsider developer. For instance, if the string contains null characters, than there is a high probability that it is not a string at all but an array of bytes. An in such a case the std::vector or your own custom classes should be used instead.

Bugs Found

Checked Projects
Collected Errors
14 435
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →