且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

基类中的非虚析构函数,但派生类中的虚析构函数会导致分段错误

更新时间:2022-05-07 00:16:43

答案真的在于声明:

    Base* virtual_derived = new VirtualDerived;

您正试图释放'malloc'未返回的地址。要了解原因,请将此行替换为

You are trying to 'free' an address that was not returned by 'malloc'. To understand why, replace this line with

    VirtualDerived* x = new VirtualDerived;
    Base* virtual_derived = x;

如果您打印这两个地址,您会注意到'x'和'virtual_derived'具有不同的值。 'malloc'返回的地址(通过'new')是'x',传递给'free'的地址(通过'delete')是'virtual_derived'。

If you print these two addresses, you will notice that 'x' and 'virtual_derived' have different values. The address that 'malloc' returned (via 'new') is 'x' and the address that was passed to 'free' (via 'delete') is 'virtual_derived'.