1

I know that p does not point to the starting address of the B object, which causes the error of free() function, but how to correct it?

Also, how do I use g++ to see the memory layout of a C++ class?

#include <iostream>
using namespace std;

class A {
public:
    virtual void show() { cout << "A::show()" << endl; }
private:
    int a;
};

class B : virtual public A {
public:
    void show() { cout << "B::show()" << endl; }
private:
    int b;
};

int main() {
    A* p = new B();
    p->show();
    delete p;
    
    return 0;
}

Output:

B::show()
free(): invalid pointer
Aborted (core dumped)

g++ 8.4.0

xushun
  • 11
  • 1
  • 2
    You definitely need a virtual destructor whenever `delete` gets a pointer type that is different to what `new` gave you. – StoryTeller - Unslander Monica Aug 26 '22 at 10:10
  • My Visual Studio 2022 C++ compiled code doesn't give me error. You need a virtual destructor in case you want that the ~B() is called but in your case just the ~A() is called. Virtual destructors are not mandatory – Marco Beninca Aug 26 '22 at 10:15

0 Answers0