我想在gcc8.2下启用数组边界检查,这样可以帮助检查编译期间数组下标是否越界,它可能会给出如下警告:
array subscript is above array bounds [-Warray-bounds]
我使用coliru做了一个演示:
#include <iostream>
struct A
{
int a;
char ch[1];
};
int main()
{
volatile A test;
test.a = 1;
test.ch[0] = 'a';
test.ch[1] = 'b';
test.ch[2] = 'c';
test.ch[3] = 'd';
test.ch[4] = '\0';
std::cout << sizeof(test) << std::endl
<< test.ch[1] << std::endl;
}
使用命令编译并运行:
g++ -std=c++11 -O2 -Wall main.cpp && ./a.out
输出如下所示,没有任何警告或错误。
8
b
那么gcc8.2支持数组边界检查吗?如何启用它?
编辑:
更进一步,根据第一个答案,如果删除volatile
in line volatile A test;
,是否可以启用数组边界检查?
谢谢。