【发布时间】:2016-11-18 12:49:41
【问题描述】:
我正在尝试使用-fsanitize=bounds 选项在我的代码中找出越界问题,但我遇到了奇怪的行为:
例如在下面的代码中:
#include <cstdlib>
#include <array>
int main (int, char **)
{
std::array <char, 1> a;
const char b = a [X]; // X <--- put index here!
return EXIT_SUCCESS;
}
使用选项编译:$ g++ -std=c++11 -fsanitize=bounds -O0 main.cpp -o main。
如果我尝试访问索引大于 1 的元素,则会报告错误:
/usr/include/c++/5/array:53:36: runtime error: index 2 out of bounds for type 'char [1]'.
但如果我尝试访问索引为 1 的元素,一切正常且不会报告错误。
这是预期的行为吗?可能是我错过了什么?
该示例已在以下位置进行测试:
-
$ g++ --version g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609; -
$ g++ --version g++ (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005。
更新
我在 GCC 6 中尝试了 -fsanitize=bounds-strict 并得到了相同的结果。
【问题讨论】:
-
未定义的行为是未定义的。
-
@AlgirdasPreidžius,我的问题是关于使用
ubsan工具而不是关于语言。 -
你到底为什么要使用带有 N == 1 的 std::array 并引用超出范围的索引?
-
@foxfireee,如果它让你高兴,你可以使用 N==1024*1024 并尝试访问循环内某处的元素 1024*1024。
-
我在发表评论:一种可能的解决方法是使用
-D_GLIBCXX_DEBUG来诊断越界访问。默认情况下,MSVC 在调试模式下也会这样做。