Why does that work?
#include <iostream>
using namespace std;
int main() {
float* tab[3];
int i = 0;
while(i < 3) {
tab[i] = new float[3-i];
i++;
}
cout << tab[2][7] << endl;
tab[2][7] = 6.87;
cout << tab[2][7] << endl;
i = 0;
while(i < 3)
delete[] tab[i];
}
while this one doesn't?
#include <iostream>
using namespace std;
int main() {
float* tab = new float[3];
cout << tab[7] << endl;
tab[7] = 6.87;
cout << tab[7] << endl;
delete[] tab;
}
I tried both programs on Win XP with MS VS 2008, both compiled without errors and the first one ran without any errors. The second made pop up some error window, however I can't remember it and can't reproduce (no access to Windows at the moment).
I tried them also on Linux (Kubuntu 10.10 with precompiled kernel package version 2.6.35.23.25) with g++ and both compile and run without any errors.
Why? Shouldn't there be any pop-ups with something like "Wrong access to unallocated memory"?
I know it should (and, luckily, does) compile without errors, but I thought it shouldn't run without them... And why the second example makes errors on Windows and not on Linux?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…