'GCC - no warning about an uninitialized array with -O0

My GCC 7.3.0 and 8.2.0 has some strange behavior I can't explain. This program, which obviously ends in a Segmentation fault:

int main()
{
    double array[2]={0, 0};
    printf("%f\n", array[999]);

    return 0;
}

Compiled with

gcc -Wall -O2 main.c

Produces the warning

main.c: In function 'main':
main.c:6:5: warning: 'array[999]' is used uninitialized in this function [-Wuninitialized]
     printf("%f\n", array[999]);
     ^~~~~~~~~~~~~~~~~~~~~~~~~~

But with optimization turned off:

gcc -Wall main.c

it produces no warning at all. My Code linter and Debug compile (gcc -g) uses -O0 and didn't pick up on a similar out of bounds error I made, until I compiled it as Release with Optimization turned on. Setting -O1 in the linter posts the warning as expected.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source