简体   繁体   中英

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]

I made a demo using 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? how to enable it?

Edit:

To be further, based on the first answer , if remove the volatile in line 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. To enable that checking, use -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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM