Segmentation fault: in vtable for __cxxabiv1::__si_class_type_info () ?

类 Demo 里声明了一个虚函数,为什么调用虚函数时core 了呢?

core 信息:

Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000aab1a12ab in vtable for __cxxabiv1::__si_class_type_info () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
class Demo {
public:
    virtual int32_t Demo() {
         return 0;
    }
};

int main() {
    Demo* d = new Demo();
    d->show(); // core 到这里了
      return 0;
}
阅读 4k
2 个回答

这个问题的错误关键提示信息是这个位置
图片.png

这个错误通常被称为段错误,意思是内存访问违反了计算机的地址空间限制。在这种情况下,发生了一个访问虚拟地址未映射到物理地址的错误。 简单一句话解释就是内存未释放。
要解决这个问题,可以考虑使用智能指针的方法,具体可看我去年时候的一篇segment博客
c++内存泄漏与智能指针

大致解释了问题,我们再返回到本问题来看,要解决此问题,我们可以使用 delete 来释放分配的资源。

#include <memory> 
using namespace std; 
class Demo { 
public: 
    virtual int32_t Demo() { 
        return 0; 
    } 
}; 
int main() { 
    Demo* d = new Demo(); 
    unique_ptr<Demo> d_ptr(d); 
    d->show(); // core 到这里了 
    delete d; 
    return 0; 
} 

你可以看到,当 d 指向的实例不再需要时,我们将其从 d_ptr 中删除。这样就可以避免在使用动态分配内存后立即访问该内存而导致的内存访问错误。

你的代码能编译么, 是不是写错代码了.

#include <cstdint>

class Demo
{
  public:
    virtual int32_t show()
    {
        return 0;
    }
};

int main()
{
    Demo *d = new Demo();
    d->show(); // core 到这里了
    return 0;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题