1

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?

ks1322
  • 33,961
  • 14
  • 109
  • 164
  • Because when obtaining a C string with https://en.cppreference.com/w/cpp/string/basic_string/c_str it should be null terminated. If `std::string` returns pointer to internal buffer, zero terminator should be already in that buffer. – ks1322 Dec 15 '20 at 20:07

2 Answers2

1

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

Daniel Marjamäki
  • 2,907
  • 15
  • 16
0

Based on Will std::string always be null-terminated in C++11?, the standard guarantees that the std::string is 0-terminated [internally].

However, this doesn't allow you to reference that 0 directly, so the cppcheck is technically correct.

Update

As Thomas pointed out in the comment, you can in fact reference that 0-terminator SINCE C++ 11.

cppcheck has a setting to conform to particular standard: --std=<id> (https://linux.die.net/man/1/cppcheck)

See if that changes its behavior.

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
  • No, `cppcheck --std=c++11` does not change anything. Also `--std=c++11` is default in cppcheck, so that plain `cppcheck` without any options is the same as `cppcheck --std=c++11`, see https://linux.die.net/man/1/cppcheck. – ks1322 Dec 16 '20 at 11:05