Must new always be followed by delete? [duplicate]
-
23-08-2019 - |
Question
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?
Solution
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.
OTHER TIPS
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.
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)
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.
You are perfectly free to forget to delete things.
Do you like wasting memory?
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.