Behaviour of malloc with delete in C++

Solution 1:

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.

Solution 2:

then there should be some error

There is. It is just not necessarily apparent.

The C++ standard (and the C standard, on which the C++ standard is modeled) call this kind of error undefined behavior. By undefined they mean that anything at all may happen. The program may continue normally, it may crash immediately, it may produce a well-defined error message and exit gracefully, it may start exhibiting random errors at some time after the actual undefined behavior event, or invoke nasal demons.

It is your responsibility to watch out and eliminate these errors. Nothing is guaranteed to alert you when they happen.

Solution 3:

Use free() not delete.

if you malloc you then have to call free to free memory.

if you new you have to call delete to free memory.

Here is a link that explains it.