What is the result if I use free new or removable with malloc?

Is it a compiler error or a 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 cannot be compiled using a virtual function if I declare a Base class as follows

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

The code below can be compiled all the time, regardless of whether the function is virtual or not.

 class Base{ void g(); void h(); }; int main() { Base* p = (Base*)malloc(sizeof(Base)); delete p; return 0; } 
+4
source share
3 answers

Undefined result, plus malloc () does not call constructors, and free () does not call destructors.

+11
source

As the comment says, the result is that the behavior of the program is undefined.

If you have a "new" with a "free", your destructors are not called. This usually results in a memory and resource leak.

If you have "malloc" with "delete", you do not receive constructor calls, so your objects are not initialized. This can lead to all kinds of errors, for example. when the destructor is called.

As stated in a comment below, in Non-POD types (such as classes that have virtual methods and classes that use virtual inheritance) that need to be initialized, even if it is not immediately obvious that constructor initialization is required. If you are a malloc object, then call the virtual method, the most likely result will be a failure of your program.

Until now, if all of your POD types (Plain Old Data) are lucky, but it depends a lot on your compiler - there is no guarantee that "malloc" and "new" use the same heap, so you may get damaged heaps and crashes on some compilers.

In short - do not do this.

+3
source

This behavior is undefined. This means that something can happen - the program can succeed, it can work hard, it can fail powerlessly and crash much later in the unrelated innocent looking part of the code, or it can even erase your hard drive.

Anything can happen since you are doing something that the C ++ standard is talking about.

+1
source

Source: https://habr.com/ru/post/1305392/


All Articles