How can a C++ program print either 0 or 1 depending on compilation options?

  c++, compiler-optimization

I have the following C++ code. It should print 1. There is only one illegal memory access and it is a reading one, i.e., for i=5 in the for loop, we obtain c[5]=cdata[5] and cdata[5] does not exist. Still, all writing calls are legal, i.e., the program never tries to write to some non-allocated array cell. If I compile it with g++ -O3, it prints 0. If I compile without -O3 it prints 1. It’s the strangest error I’ve ever seen with g++.

#include <iostream>
#include <cstdlib>
using namespace std;
int n,d;
int *f, *c;
void loadData(){
    int fdata[] = {7,  2, 2, 7, 7, 1};
    int cdata[] = {66, 5, 4, 3, 2};
    n = 6;
    d = 3;
    f = new int[n+1];
    c = new int[n];
    f[0] = fdata[0];
    c[0] = cdata[0];
    for (int i = 1;i<n;i++){
        f[i] = fdata[i];
        c[i] = cdata[i];
int main(){

Source: Windows Questions C++