Behaviour of malloc with delete in C++

Luv picture Luv · Jun 1, 2012 · Viewed 28.4k times · Source
int *p=(int * )malloc(sizeof(int));

delete p;

When we allocate memory using malloc then we should release it using free and when we allocate using new in C++ then we should release it using delete.

But if we allocate memory using malloc and then use delete, then there should be some error. But in the above code there's no error or warning coming in C++.

Also if we reverse and allocate using new and release using free, then also there's no error or warning.

Why is it so?

Answer

Cat Plus Plus picture Cat Plus Plus · Jun 1, 2012

This is undefined behaviour, as there's no way to reliably prove that memory behind the pointer was allocated correctly (i.e. by new for delete or new[] for delete[]). It's your job to ensure things like that don't happen. It's simple when you use right tools, namely smart pointers. Whenever you say delete, you're doing it wrong.