C++ is it necessary to delete dynamically allocated objects at the end of the main scope?

Most of the modern OS always reclaim back all memory they allocated to a program(process).
The OS doesn’t really understand if your program leaked memory it merely takes back what it allocatted.

But there are bigger issues at hand than just the memory loss:

Note that if the destructor of the object whos delete needs to be called performs some non-trivial operation and your program depends on the side effects produced by it then your program falls prey to Undefined Behavior[Ref 1]. Once that happens all bets are off and your program may show any beahvior.

Also, An OS usually reclaims the allocated memory but not the other resources, So you might leak those resources indirectly. This may include operations dealing with file descriptors or state of the program itself etc.

Hence, it is a good practice to always deallocate all your allocations by calling delete or delete [] before exiting your program.


[Ref 1]C++03 Standard 3.8 Para 4:

“….if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.”

Leave a Comment