Non virtual destructor in base class, but virtual destructor in derived class cause segmentation fault

倾然丶 夕夏残阳落幕 提交于 2019-12-05 05:45:15

The answer really lies in the statement:

    Base* virtual_derived = new VirtualDerived;

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;

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'.

You have to declare the destructor in the base class as virtual, which you do not do in this example. Declaring it as virtual in the derived class only is not sufficient.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!