Consider this small program:
int main(int argc, const char *argv[])
{
int *i = new int;
//do something with i, where i is involved all the time
return 0;
}
As a matter of good style and to show that you actually know you must free memory allocated on the heap you normally add delete i;
just before return statement.
But will it do any harm if leaving delete i;
out?
UPDATE: Please do not flame each other in comments. I do know that just to be on safe side and just as the matter of good style and so on I should free allocated memory. The question is, can it be ommitted safely in this particular case.
It shouldn't matter, since modern operating systems tend to clean up a program's memory after the program terminates. That being said, I'm pretty sure some older systems don't do the clean up, so if you're targeting any of those systems then you'll definitely want to be careful.
Regardless of both those points, wouldn't you sleep better knowing that your code doesn't leak?
No, it won't do any harm as the system cleans all of the non deleted ones automatically.
the harm will if you write code that excepts to use everything until the program terminates, and then you discover you need to run it multiple times and you will have memory leaks between iterations.
If 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