When using dynamically allocated objects in C++ eg:
TGraph* A = new TGraph(...);
One should always delete
these because otherwise the objects might still be in memory when
control is handed back to the parent scope. While I can see why this is true for subscopes and subroutines of a program, does the same count for the main
scope?
Am I obliged to delete
objects that were dynamically built inside main()
? The reason why this seems a bit redudant to me is that when main
ends, the program also ends, so there is no need to worry about memory leaks.
You're right, but consider this: you create a class object which opens a connection to remote DB. After your program will complete, you should tell the DB "I'm done, i'm going to disconnect", but it won't happen in the case you won't call delete properly.
Yes, you should call
delete
, at least because it's best practice. If you have important logic in your destructor, that's one extra reason that you should calldelete
.Corrected: If the program depends on logic in the destructor, not calling
delete
explicitly results in undefined behavior.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
ordelete []
before exiting your program.[Ref 1]C++03 Standard 3.8 Para 4:
Its the best practice to de-allocate memory that's been allocated. You should keep in mind that Heap memory is limited and just allocating with out de-allocating while your program is running might run the heap space out for some other/or the same program(if its some kind of a daemon that is meant to run for a very long time) that needs heap.
Of course memory will be reclaimed by the operating system at the end of the program's execution.
I see you are using ROOT (CMS guy?). I think ROOT takes care of this and cleans up, doesn't it?
Best practices:
new
, use automatic allocationYou should never have to write
delete
in applicative code.Here, why are you calling
new
forTGraph
?works better: less worries!