Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 616
Luv Avatar asked Jun 01 '12 16:06

Luv


People also ask

Can you use Delete with malloc?

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.

How do I delete a memory created by malloc?

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.

What will happen if you malloc and free instead of 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.

What is the difference between free () and delete?

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.


1 Answers

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.

like image 90
Cat Plus Plus Avatar answered Oct 14 '22 11:10

Cat Plus Plus