是cppcheck的误报containerOutOfBoundsIndexExpression错误吗?
Is it false positive containerOutOfBoundsIndexExpression error of cppcheck?
我想用 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()]
应该 return 0
字符,但 cppcheck return 是一个错误。是不是cppcheck的误报?
基于Will std::string always be null-terminated in C++11?,标准保证std::string
[内部]以0结尾。
但是,这不允许您直接引用 0
,因此 cppcheck 在技术上是正确的。
更新
正如 Thomas 在评论中指出的那样,您实际上可以引用 0 终止符 SINCE C++ 11.
cppcheck 具有符合特定标准的设置:--std=<id>
(https://linux.die.net/man/1/cppcheck)
看看这是否改变了它的行为。
我认为这是误报。我创建了这张票:https://trac.cppcheck.net/ticket/10048
我想用 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()]
应该 return 0
字符,但 cppcheck return 是一个错误。是不是cppcheck的误报?
基于Will std::string always be null-terminated in C++11?,标准保证std::string
[内部]以0结尾。
但是,这不允许您直接引用 0
,因此 cppcheck 在技术上是正确的。
更新
正如 Thomas 在评论中指出的那样,您实际上可以引用 0 终止符 SINCE C++ 11.
cppcheck 具有符合特定标准的设置:--std=<id>
(https://linux.die.net/man/1/cppcheck)
看看这是否改变了它的行为。
我认为这是误报。我创建了这张票:https://trac.cppcheck.net/ticket/10048