2

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?

Bernhard Barker
  • 50,899
  • 13
  • 85
  • 122

3 Answers3

0

Class Sub does not inherit from class Super, so they aren't related in any way as currently written.

Joe
  • 38,368
  • 16
  • 103
  • 119
0

Can this code compile at all?

  • All your methods are private.
  • There is no inheritance between Sub and Super.
  • The constructor are wrongly named.
  • The main() function does not return int.

Fixing all these results in a code that compiles and runs without a segfault.

adl
  • 14,456
  • 6
  • 45
  • 62
  • Yes this code compiles and executes.. that is why I am getting a seg fault. Its a c++ code, I think you are confusing it with some other language (java probably....). Anyway help if you find someting... cheers. – Rohit Chauhan Apr 11 '11 at 04:05
  • The code did not look the way it looks now when I (and Joe) answered. The first three points have been fixed. It is still invalid C++ because main() should return int (http://stackoverflow.com/questions/204476/what-should-main-return-in-c-c), but that would not justify a segfault. – adl Apr 11 '11 at 06:15
0

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:

  • add a dummy int member to the classes. It might be that a zero-sized class causes wrong code generation.
  • declare 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?

sam hocevar
  • 11,037
  • 5
  • 42
  • 59