1

我想在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支持数组边界检查吗?如何启用它?

编辑:

更进一步,根据第一个答案,如果删除volatilein line volatile A test;,是否可以启用数组边界检查?

谢谢。

4

1 回答 1

6

默认情况下,-Warray-bounds不会对结构末尾的数组发出警告,大概是为了避免对预标准化灵活数组成员的误报。要启用该检查,请使用-Warray-bounds=2. 演示

另请注意,-Warray-bounds仅当-ftree-vrp标志处于活动状态时才有效,默认情况下处于-O2或更高。

于 2019-08-01T02:48:54.667 回答