Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In my C++ main function, for example, if I had a pointer to a variable which uses heap memory (as opposed to stack memory) - is this automatically deallocated after my application exits? I would assume so.

Even so, is it good practice to always delete heap allocations even if you think they will never be used in a situation where the memory is automatically deallocated on exit?

For example, is there any point in doing this?

int main(...) {     A* a = new A();     a->DoSomething();     delete a;     return 0; } 

I was thinking maybe in case I refactor (or someone else refactors) that code and puts it elsewhere in the application, where delete is really necessary.

As well as the answer by Brian R. Bondy (which talks specifically about the implications in C++), Paul Tomblin also has a good answer to a C specific question, which also talks about the C++ destructor.

like image 745
Nick Bolton Avatar asked Mar 24 '09 15:03

Nick Bolton


People also ask

What is the purpose of delete operator in C?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

Do you have to use delete with new?

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.

What happens when delete is called?

Two things happen when delete[] is called: If the array is of a type that has a nontrivial destructor, the destructor is called for each of the elements in the array, in reverse order. The memory occupied by the array is released.

Can you use Delete in C?

There's no new / delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.


1 Answers

It is important to explicitly call delete because you may have some code in the destructor that you want to execute. Like maybe writing some data to a log file. If you let the OS free your memory for you, your code in your destructor will not be executed.

Most operating systems will deallocate the memory when your program ends. But it is good practice to deallocate it yourself and like I said above the OS won't call your destructor.

As for calling delete in general, yes you always want to call delete, or else you will have a memory leak in your program, which will lead to new allocations failing.

like image 123
Brian R. Bondy Avatar answered Oct 19 '22 14:10

Brian R. Bondy