【发布时间】:2020-12-15 19:42:26
【问题描述】:
我想用 cppcheck 工具检查以下代码:
void f()
{
std::string str = "123";
const char* end = &str[str.size()];
}
但是当我运行 cppcheck 时,它会报告以下我认为是误报的错误:
$ 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()];
^
据我了解,std::string 应存储终止空字符以及字符串的其余字符,因此 str[str.size()] 应返回 0 字符,但 cppcheck 返回错误。是cppcheck误报吗?
【问题讨论】:
-
因为在使用en.cppreference.com/w/cpp/string/basic_string/c_str 获取C 字符串时,它应该以null 结尾。如果
std::string返回指向内部缓冲区的指针,则零终止符应该已经在该缓冲区中。