I have this simple loop, running through an array of base class pointers:
Object * objects[2];
objects[0] = new GreenObject;
objects[1] = new RedObject;
objects[2] = new BlueObject;
for (int i = 0; i < 3; ++i) {
cout << i << " ";
objects[i]->info();
}
Under debug mode, the program crashes on the third iteration of the loop, immediately after outputting i, when the info() method is invoked. No such thing happens in release mode, it is running as it should. It is not an issue of the object, since it locks up even if I use other derived classes.
GCC 4.4.0 under Windows 7 64bit
Any ideas?
This is (and
forloop) going beyond the end of the array:causing undefined behaviour. The fact it runs in release is just (un)lucky. A subset of undefined behaviour is it behaves as you expect.
Array indexes run from
0toN - 1, whereNis the number of elements in the array. In the case ofobjectsthe valid indexes are0and1only. Change the declaration ofobjectsto: