其他分享
首页 > 其他分享> > c – 删除指针的分段错误

c – 删除指针的分段错误

作者:互联网

#include <iostream>
using namespace std;
class c1 {};
class c2 : public c1 {};
class c3 : public c1 {};
class c4 : public c2, public c3 {};

int main () {
  c4 *x1 = new c4;
  c3 *x2 = x1;
  delete x2; // segmentation fault
}

嗨,我想了解类型转换和继承,我发现了这个问题.我有一个指向最派生类的指针,并且对任何类中间进行了类型化(隐式),而删除时,我认为它应该能够通过第一个新删除已分配的空间.在一些编译器中,它似乎很好,但在linux gcc版本4.7.2(Debian 4.7.2-5)中,它给出了分段错误.无法弄清楚,为什么?任何帮助/指针/建议将不胜感激.

注 – 类是以钻石问题的形式派生的.

解决方法:

这是未定义的行为.正如您所见,在某些情况下它似乎运作良好,在某些情况下它不会.

至少基类c3(或c1和c2)应该有一个虚析构函数.例如

class c3 : public c1 {
public:
    virtual ~c3() {}
};

根据标准,$5.3.5/3 Delete [expr.delete]

(强调我的)

In the first alternative (delete object), if the static type of the
object to be deleted is different from its dynamic type, the static
type shall be a base class of the dynamic type of the object to be
deleted and the static type shall have a virtual destructor or the
behavior is undefined
.

标签:c,language-lawyer,pointers,segmentation-fault,delete-operator
来源: https://codeday.me/bug/20190823/1701609.html