加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c:下面一段代码崩溃了

发布时间:2020-12-16 10:54:20 所属栏目:百科 来源:网络整理
导读:#include iostreamusing namespace std;class B{public: B() { cout "Base B()" endl; } ~B() { cout "Base ~B()" endl; }private: int x;};class D : public B{public: D() { cout "Derived D()" endl; } virtual ~D() { cout "Derived ~D()" endl; }};intm
#include <iostream>
using namespace std;

class B
{
public:
    B() { cout << "Base B()" << endl; }
    ~B() { cout << "Base ~B()" << endl; }
private:
    int x;
};

class D : public B
{
public:
    D() { cout << "Derived D()" << endl; }
    virtual ~D() { cout << "Derived ~D()" << endl; }
};

int
main ( void )
{
    B* b = new D;
    delete b;
}


---- output----------
Base B()
Derived D()
Base ~B()
*** glibc detected *** ./a.out: free(): invalid pointer: 0x0930500c ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6[0xb7d41604]
/lib/tls/i686/cmov/libc.so.6(cfree+0x96)[0xb7d435b6]
/usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0xb7f24231]
./a.out[0x8048948]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb7ce8775]
./a.out[0x80487c1]
Aborted

如果我从基类中删除私有成员“int x”,它工作正常

解决方法

你正在做的是UB,但对于你正在使用的特定编译器行为可以描述如下.为了简化下面的ASCII图形,修改示例,将y成员添加到D并修改main.

#include <iostream>
using namespace std;

class B
{
public:
    B() { cout << "Base B()" << endl; }
    ~B() { cout << "Base ~B()" << endl; }
private:
    int x;
};

class D : public B
{
public:
    D() { cout << "Derived D()" << endl; }
    virtual ~D() { cout << "Derived ~D()" << endl; }
private:
    int y; // added.
};

int
main ( void )
{
    D* d = new D; // modified.
    B* b = d;
    delete b;
}

在您使用的编译器中,vtable(如果有)放在内存块的开头.
在编译器中,您使用的内存布局如下:

+--------+
| vtable | <--- d points here,at the start of the memory block.
+--------+
| x      | <--- b points here,in the middle of the memory block.
+--------+
| y      |
+--------+

稍后当调用delete b时,程序将尝试使用b指针释放内存块,b指针指向内存块的中间.

这将导致由于无效指针错误导致的崩溃.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读