[英]GCC8.2 How to enable warning: array subscript is above array bounds [-Warray-bounds]
I want to enable array boundary checking under gcc8.2, so it can help to check if array subscript is out of bound during compilation period, it may give the warning like: array subscript is above array bounds [-Warray-bounds]
我想在gcc8.2下启用数组边界检查,因此它可以帮助检查在编译期间array subscript is above array bounds [-Warray-bounds]
,它可能会发出如下警告: array subscript is above array bounds [-Warray-bounds]
I made a demo using coliru : 我使用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;
}
Compile and run with command: 编译并运行以下命令:
g++ -std=c++11 -O2 -Wall main.cpp && ./a.out
Output is shown below, without any warning or error. 输出显示如下,没有任何警告或错误。
8
b
So does gcc8.2 support array boundary checking? 那么gcc8.2是否支持数组边界检查? how to enable it? 如何启用它?
Edit: 编辑:
To be further, based on the first answer , if remove the volatile
in line volatile A test;
进一步地,根据第一答案 ,如果去除在线volatile A test;
中的volatile
volatile A test;
, is it possible to enable array boundary checking? ,是否可以启用数组边界检查?
Thanks. 谢谢。
By default, -Warray-bounds
doesn't warn for arrays at the end of a structures, presumably to avoid false-positives on pre-standardization flexible array members. 默认情况下, -Warray-bounds
不会在结构末尾警告数组,以免避免标准化前的灵活数组成员出现假阳性。 To enable that checking, use -Warray-bounds=2
. 要启用该检查,请使用-Warray-bounds=2
。 Demo . 演示
Note also that -Warray-bounds
only works when the -ftree-vrp
flag is active, which it is by default at -O2
and higher. 还要注意, -Warray-bounds
仅在-ftree-vrp
标志处于活动状态时才起作用,默认情况下,它在-O2
及更高版本中有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.