Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should memory be freed just before return statement in main?

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.

like image 208
Roman Byshko Avatar asked Dec 16 '22 06:12

Roman Byshko


2 Answers

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?

like image 89
Ken Wayne VanderLinde Avatar answered Feb 15 '23 23:02

Ken Wayne VanderLinde


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.

like image 22
Dani Avatar answered Feb 16 '23 00:02

Dani