What is the use of malloc
and free
when we have new
and delete
in C++. I guess function of both free
and delete
is same.
We use new and delete operators in C++ to dynamically allocate memory whereas malloc () and free () functions are also used for the same purpose in C and C++. The functionality of the new or malloc () and delete or free () seems to be the same but they differ in various ways.
new calls a constructor, malloc () does not. delete calls a destructor, free () does not. If the class in question allocates memory internally, then yes, you are likely to encounter a memory leak.
Behaviour of malloc with delete in C++. 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.
malloc/ free Allocate / release memory Memory allocated from 'Heap'. Returns a void*. Returns NULLon failure. Must specify the size required in bytes. Allocating array requires manual calculation of space. Reallocating larger chunk of memory simple (no copy constructor to worry about). They will NOTcall new/ delete.
They're not the same. new
calls the constructor, malloc
just allocates the memory.
Also, it's undefined behavior mixing the two (i.e. using new
with free
and malloc
with delete
).
In C++, you're supposed to use new
and delete
, malloc
and free
are there for compatibility reasons with C.
In C++, it is rarely useful that one would use malloc
& free
instead of new
& delete
.
One Scenario I can think of is:
If you do not want to get your memory initialized by implicit constructor calls, and just need an assured memory allocation for placement new then it is perfectly fine to use malloc
and free
instead of new
and delete
.
On the other hand, it is important to know that malloc
and new
are not same!
Two important differences straight up are:
new
guarantees callng of constructors of your class for initializing the class members while malloc
does not, One would have to do an additional memset
or related function calls post an malloc
to initialize the allocated memory to do something meaningful.
A big advantage is that for new
you do not need to check for NULL
after every allocation, just enclosing exception handlers will do the job saving you redundant error checking unlike malloc
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With