I've got this code snippet, it tries to call virtual function through an object's vptr (pointing to virtual function table) and uses object pointer to convert to p->vptr, like this:
#include<iostream>
using namespace std;
struct C {
virtual int f() {
return 7;
}
};
typedef int (*pf)();
int main() {
C c1;
pf *pvtable = (pf *) &c1;
cout << (*pvtable[0])() << endl;
return 0;
}
I used clang++14 to compile/link. On running it, programs returns 139, and no cout line is shown, seems it has crashed.
Why it doesn't work and how to fix it?