Reputation: 19
Why do we need to explicitly delete dynamically allocated memory, when the OS itself takes back memory of process? In the kind of situation where dynamic memory is allocated inside a constructor, why do we need to delete it in the destructor?
Upvotes: 0
Views: 1085
Reputation:
The OS recycle of memory will only happen after/during the termination of the program.
If you are writing a program that persists for a long time, such as a background daemon running as long as the PC is on, due to unfreed memory created during the operation, your PC's memory resource will eventually get used up, triggering the Low Memory Killer of your OS, which kills some programs (which may include yours) and triggers the recycling until the system has enough memory again. From a stability perspective you want to avoid this as much as possible.
Upvotes: 0
Reputation: 16869
To some extent, you do not have to explicitly delete allocated memory. You can let memory leaks accumulate until your program ends and the OS reclaims the memory for you. A better question is do you want to?
The OS will not reclaim the memory until your process ends. Can you afford to wait that long? If you allocate less than a megabyte of memory over the course of your program, you are likely to not see bad side-effects. However, if your program could be run for hours, or even days, how much memory is then leaked? Eventually you get to the point where other programs are slowed down because your program is hogging all the memory – and it's not even using that memory; the leaked memory is floating around unused and unusable.
If you learn to clean up after yourself while your programs are small, you'll be prepared to tackle larger projects that can potentially leak all available memory on a system. Also, it's polite to not take more than what you need (or what you've reasonably estimated as needed) of a limited resource.
Upvotes: 6
Reputation: 238311
why we need to explicitly delete dynamically allocated memory, when OS itself takes back memory of process
Because we might want the process to keep running. If you allocate a megabyte every second and don't deallocate any memory, then after a day of running the process, you've allocated 84 gigabytes. At some point you will run out of memory. It would be highly inconvenient if we had to restart all programs every few hours just to give operating system some memory back.
Upvotes: 1
Reputation: 29965
Yes, the OS will clean-up after you, but there are 2 major problems:
Having said that, you can use smart pointers and STL containers to manage memory and froget about it.
Upvotes: 1