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.
If you don't delete them, they will remain there (but won't be accessible -> this is called memory leak) until your process exits, when the operating system will deallocate them. Save this answer.
For dynamically allocated memory like “int *p = new int[10]”, it is the programmer's responsibility to deallocate memory when no longer needed. If the programmer doesn't deallocate memory, it causes a memory leak (memory is not deallocated until the program terminates).
The C++ keyword delete is used to release dynamically allocated memory so that it may be reused. Dynamic variables (memory allocated by newshould be deleted when they will no longer be used. Deleted dynamic variables should NOT be reused unless that have been reallocated with another call tonew.
It is the programmer's job to deallocate dynamically created space. To de-allocate dynamic memory, we use the delete operator.
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."
IMO it is best to always call delete
properly:
main
scopeIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With