What's the outcome if I use free with new or delete with malloc?

Posted by skydoor on Stack Overflow See other posts from Stack Overflow or by skydoor
Published on 2010-03-28T22:27:44Z Indexed on 2010/03/28 22:33 UTC
Read the original article Hit count: 105

Filed under:

It is a compiler error or runtime error? The code below can be compiled!

class Base{
void g();
void h();
};

int main()
{
    Base* p = new Base();
    free(p);
return 0;
}

However it can't be compiled with a virtual function if I declare the class Base like this

class Base{
virtual void g();
void h();
};

The code below can be compiled all the time, no matter the function is virtual or not.

class Base{
void g();
void h();
};

int main()
{
    Base* p = (Base*)malloc(sizeof(Base));
    delete p;
return 0;
}

© Stack Overflow or respective owner

Related posts about c++