tags:

views:

546

answers:

6

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

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?

A: 

You are perfectly free to forget to delete things.

Do you like wasting memory?

Joshua
+1  A: 

Here no. But as the program gets larger and more complex I would manage my memory so that I can track down bugs faster. The standard says nothing but getting into good habits in the smaller case leads to better code long term.

ojblass
Indeed, I mean I find myself often typing out delete[] statements right before return, even though I knew (on a practical level) that it made no difference. And that's not a habit I'm looking to stop either -- I was just interested the extent to which the standard recommended it.
GRB
+5  A: 

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.

Reed Copsey
A: 

I don't know the Standard, but there is a whole programming style around this question: crash-only softxare Theoretically databases or OS kernels should be developed as such, but often it's not really practical to use them like that because on restart there is some cleanup that can be long. Moreover dependent systems (programs inside an OS or database clients) might not be crash-only.

nraynaud
+5  A: 

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.

Brian Campbell
I missed that one! :)
Mitch Wheat
Yes, it was actually kind of hard to find; you beat me to the post since I took the time to find that one article, as I knew it had been asked in the last few days.
Brian Campbell