Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must new always be followed by delete? [duplicate]

I think we all understand the necessity of delete when reassigning a dynamically-allocated pointer in order to prevent memory leaks. However, I'm curious, to what extent does the C++ mandate the usage of delete? For example, take the following program

int main()
{
     int* arr = new int[5];
     return 0;
}

While for all intents and purposes no leak occurs here (since your program is ending and the OS will clean up all memory once it returns), but does the standard still require -- or recommend -- the usage of delete[] in this case? If not, would there be any other reason why you would delete[] here?

like image 665
GRB Avatar asked Apr 04 '09 02:04

GRB


3 Answers

Dupe of Is there a reason to call delete in C++ when a program is exiting anyway?

Answer is that because of destructors that need to be run, it is sometimes necessary to delete the object before exiting the program. Also, many memory leak detection tools will complain if you don't do this, so to make it easier to find real memory leaks, you should try and delete all of your objects before exiting.

like image 129
Brian Campbell Avatar answered Sep 21 '22 04:09

Brian Campbell


There is nothing that requires a delete[] in the standard - However, I would say it is a very good guideline to follow.

However, it is better practice to use a delete or delete[] with every new or new[] operation, even if the memory will be cleaned up by the program termination.

Many custom objects will have a destructor that does other logic than just cleaning up the memory. Using delete guarantees the destruction in these cases.

Also, if you ever move around your routines, you are less likely to cause memory leaks in other places in your code.

like image 35
Reed Copsey Avatar answered Sep 22 '22 04:09

Reed Copsey


Please see:

When to use "new" and when not to, in C++?

About constructors/destructors and new/delete operators in C++ for custom objects

delete and delete [] the same in Visual C++?

Why is there a special new and delete for arrays?

How to track memory allocations in C++ (especially new/delete)

Array of structs and new / delete

What is the difference between new/delete and malloc/free?

like image 24
Mitch Wheat Avatar answered Sep 22 '22 04:09

Mitch Wheat