开发者

Is leaked memory freed up when the program exits?

If I programmed — without knowing it — a memory leak, and the applicatio开发者_开发知识库n terminates, is the leaked memory freed?


Yes, a "memory leak" is simply memory that a process no longer has a reference to, and thus can no longer free. The OS still keeps track of all the memory allocated to a process, and will free it when that process terminates.

In the vast majority of cases the OS will free the memory - as is the case with normal "flavors" of Windows, Linux, Solaris, etc. However it is important to note that in specialized environments such as various Real-Time Operating Systems the memory may not be freed when the program is terminated.


The OS executing your program usually does cleanup memory that is not freed explicitly and handles that are not closed explicitly, but this is not guaranteed by the C++ standard. You may find some embedded device that do not free up your memory leaks.

That being said Windows and all distros of Linux that I've ever seen do free up memory leaks.

You can easily create a huge loop of memory leaks though to test it out yourself. Watch your RAM usage grow and then close your program. You will see that the RAM usage goes back down.


Another consideration when using C++ is that if you aren't deleting your heap allocated memory then your destructors are also not being called. Sometimes you will have other side effects as well if your destructors aren't called.


Are you running on a desktop OS (Windows, Linux etc.)? If so, yes, in general the system will free any memory associated with the program when the program exits.


Usually, yes. Some systems support things like shared memory blocks that aren't automatically freed when a program exits though. Most still keep a reference count and delete it when all the programs that opened it exit, but a few don't (e.g., 16-bit Windows had a few types of items that would remain allocated even when nothing referred to them -- though it usually crashed for other reasons before enough of this accumulated to cause a problem...)


As far as I know, a modern operating system will free this memory once the program terminates.


Depends on what memory you leaked. Some memory can't be reclaimed by the OS. Most memory on most OSes however will be automatically reclaimed when the process exits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜