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?
It is perfectly legal, moral, and wholesome to use malloc() and delete in the same program, or to use new and free() in the same program.
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.
If we allocate memory using malloc, it should be deleted using free. If we allocate memory using new, it should be deleted using delete. Now, in order to check what happens if we do the reverse, I wrote a small code.
free() is a C library function that can also be used in C++, while “delete” is a C++ keyword. free() frees memory but doesn't call Destructor of a class whereas “delete” frees the memory and also calls the Destructor of the class.
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.
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