简体   繁体   English

GCC在调试模式下崩溃,在发布模式下运行正常吗?

[英]GCC crash in debug mode, runs fine in release mode?

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. 在调试模式下,调用info()方法后,在输出i之后,程序立即在循环的第三次迭代中崩溃。 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 Windows 7 64bit下的GCC 4.4.0

Any ideas? 有任何想法吗?

This is (and for loop) going beyond the end of the array: 这(和for循环)超出了数组的末尾:

objects[2] = new BlueObject;

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 0 to N - 1 , where N is the number of elements in the array. 数组索引的范围是0N - 1 ,其中N是数组中元素的数量。 In the case of objects the valid indexes are 0 and 1 only. 对于objects ,有效索引仅为01 Change the declaration of objects to: objects的声明更改为:

Object * objects[3];

Accessing objects[2] is undefined behaviour. 访问objects[2]是未定义的行为。

It's a common mistake to expect programming errors to always result in crashes or obvious failures. 期望编程错误总是会导致崩溃或明显的故障是一个常见的错误。

Undefined behaviour means anything can happen, including appearing to work in some situations. 未定义的行为意味着任何事情都可能发生,包括在某些情况下看起来可以工作。

If you want predictable, repeatable behaviour then you should write correct code. 如果您想要可预测的,可重复的行为,则应编写正确的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM