虚函数调用分段错误
每当我尝试访问虚拟函数时,都会遇到分段错误。代码基本上是这样的:
class Super {
public:
Super() { cout << "Ctor Super" << endl; }
virtual void test() = 0;
};
class Sub : public Super {
public:
Sub() { cout << "Ctor Sub" << endl; }
void test() { cout << "Test in Sub" << endl; }
};
void main()
{
Super* s = new Sub;
s->test(); // Segmentation fault So I tried the one below
Sub* s1 = new Sub;
s1->test(); //Still segmentation fault
Sub s2;
s2.test(); // Works fine BUT
Super *s3 = &s2;
s3->test(); // segmentation fault and EVEN
Sub *s4 = &s2;
s4->test(); //segmentation fault
}
我已经尝试了几乎所有我所知道的关于虚函数的东西,但它不起作用。它实际上是一个更大程序的一部分,因此可能存在一些问题,但是一旦我删除虚拟函数或停止使其虚拟,它就可以工作。有什么想法吗?
还有什么工具或方法可以检查vtable吗?
I am getting a segmentation fault whenever I am trying to access a virtual function. The code is basically like this:
class Super {
public:
Super() { cout << "Ctor Super" << endl; }
virtual void test() = 0;
};
class Sub : public Super {
public:
Sub() { cout << "Ctor Sub" << endl; }
void test() { cout << "Test in Sub" << endl; }
};
void main()
{
Super* s = new Sub;
s->test(); // Segmentation fault So I tried the one below
Sub* s1 = new Sub;
s1->test(); //Still segmentation fault
Sub s2;
s2.test(); // Works fine BUT
Super *s3 = &s2;
s3->test(); // segmentation fault and EVEN
Sub *s4 = &s2;
s4->test(); //segmentation fault
}
I have tried almost everything I know about virtual functions and it does not work. It's actually a part of a bigger program so it might have some problem there but as soon as I remove the virtual function or stop making it virtual it works. Any Ideas?
Also is there any tool or way to examine the vtable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Sub 类不继承自 Super 类,因此它们在当前编写的情况下没有任何关系。
Class Sub does not inherit from class Super, so they aren't related in any way as currently written.
这段代码可以编译吗?
修复所有这些结果会导致编译和运行时没有段错误。
Can this code compile at all?
Fixing all these results in a code that compiles and runs without a segfault.
除了编译器错误之外,我不知道是什么原因会导致该问题。能给出具体的编译器版本吗?
与此同时,我将尝试以下操作:
int
成员。零大小的类可能会导致错误的代码生成。Sub::test()
声明为虚拟。同样,编译器可能在这里行为不当。另外,您遇到了什么样的分段错误?到底是
SIGSEGV
还是另一个信号?您能否提供调试器回溯和本地程序集转储?I don’t see what could cause the problem except a compiler bug. Can you give the exact compiler version?
In the meantime, I would try the following:
int
member to the classes. It might be that a zero-sized class causes wrong code generation.Sub::test()
as virtual, too. Again, might be the compiler misbehaving here.Also, what kind of segmentation fault are you getting? Is it precisely
SIGSEGV
or is it another signal? Could you give a debugger backtrace and local assembly dump?