Search code examples
c++c++11cppcheck

Is it false positive containerOutOfBoundsIndexExpression error of cppcheck?


I have the following code which I want to check with cppcheck tool:

void f()
{
    std::string str = "123";
    const char* end = &str[str.size()];
}

But when I run cppcheck it reports the following errors which I think are false positives:

$ cppcheck oob.cpp
Checking oob.cpp ...
oob.cpp:4:27: error: Out of bounds access in 'str[str.size()]', if 'str' size is 3 and 'str.size()' is 3 [containerOutOfBounds]
    const char* end = &str[str.size()];
                          ^
oob.cpp:4:24: error: Out of bounds access of str, index 'str.size()' is out of bounds. [containerOutOfBoundsIndexExpression]
    const char* end = &str[str.size()];
                       ^

As I understand std::string should store terminating null character along with the rest characters of the string so str[str.size()] should return 0 character, but cppcheck returns an error. Is it false positive of cppcheck?


Solution

  • I believe this is a false positive. I created this ticket: https://trac.cppcheck.net/ticket/10048