#GCC -Warray-bounds comple flag

13 messages · Page 1 of 1 (latest)

golden flumeBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

acoustic token
#

use const int input = 200

#

to make that a compile-time constant

#

and also consider using the address sanitizer for dynamic checking instead

stoic ledge
#

Thay is still an out of bounds read?

#

;compile -Warray-bounds=2 -O2 -Werror

int main(void) {
    int arr[2] = {1,2};
    const int input = 200;

    int a = arr[200];
}
silk finchBOT
#
Compilation successful

No output.

buoyant minnow
#

;compile -Warray-bounds -O2

int main(void) {
    int arr[2] = {1,2};
    const int input = 200;

    int a = arr[200];
    return a; // use `a` to prevent optimization
}
silk finchBOT
#
Compiler Output
<source>: In function 'int main()':
<source>:5:20: warning: array subscript 200 is above array bounds of 'int [2]' [-Warray-bounds]
    5 |     int a = arr[200];
      |             ~~~~~~~^
<source>:2:9: note: while referencing 'arr'
    2 |     int arr[2] = {1,2};
      |         ^~~
buoyant minnow
#

Because you're not using a afterwards, so optimization probably just removes this "useless" instruction.

#

Without optimization, this instruction is kept.

golden flumeBOT
#

Thank you and let us know if you have any more questions!

buoyant minnow