简体   繁体   中英

C++ memory leak after main finishes?

is this a memory leak?, supposed Foo() is a class with a default constructor

int main()
{

   Foo * p = new Foo();

   return 0;
}

I think it is not a leak because the application ends as soon as main ends and supposedly the OS releases all the resources for that app once it is done. Is that assumption right?

Yes, in the context of your program it is a leak. You did not de-allocate your Foo .

Will your OS reclaim the process's memory anyway? Maybe, maybe not. Windows will re-use the memory, sure.

But if you want a general-purpose hyper-practical answer for your system and your system only then, yes, you might get away with this.

However, in no cases will indirect resources be magically freed by your OS. Foo 's destructor may involve more than memory de-allocation .

If you want a C++ answer, or one that has merit in terms of code integrity, intelligent design (lol) and frankly simply good habits, no . When someone asks for solid practical reasons that they must find a reason to do delete , it can be hard to justify when forced to provide examples such as file handles, network connections, and worker threads. But basic common sense dictates that all of these concerns are automatically taken care of , without you having to name each one individually , when you simply take the 5-second effort to destroy your objects when you're done with them.

Just delete it. You have no excuse not to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM