Some programs don't need to manage their dynamic memory use; they simply allocate what they need, and never worry about freeing it. This class includes compilers and other programs that run for a fixed or bounded period of time and then terminate. When such a program finishes, it automatically relinquishes all its memory, and there is little need to spend time giving up each byte as soon as it will no longer be used.
Other programs are more long-lived. Certain utilities such as calendar manager, mailtool, and the operating system itself have to run for days or weeks at a time, and manage the allocation and freeing of dynamic memory.
可见防止内存泄漏只对长时间运行的程序有意义,同时作者也说明了即使程序自己不释放内存,内存也会被自动释放,那么除了操作系统还会有谁呢?^_^
windows核心编程第71页:
虽然进程确实没有机会执行自己的清除操作,但是操作系统可以在进程之后进行全面的清
除,使得所有操作系统资源都不会保留下来。这意味着进程使用的所有内存均被释放,所有打
开的文件全部关闭,所有内核对象的使用计数均被递减,同时所有的用户对象和G D I 对象均被
撤消。一旦进程终止运行(无论采用何种方法),系统将确保该进程不会将它的任何部分遗留下
来。绝对没有办法知道该进程是否曾经运行过。进程一旦终止运行,它绝对不会留下任何蛛丝
马迹。希望这是很清楚的。
注意Te r m i n a t e P r o c e s s 函数是个异步运行的函数,也就是说,它会告诉系统,你想要
进程终止运行,但是当函数返回时,你无法保证该进程已经终止运行。因此,如果想
要确切地了解进程是否已经终止运行,必须调用Wa i t F o r S i n g l e O b j e c t 函数(第9 章介绍)
或者类似的函数,并传递进程的句柄。
进程中的线程何时全部终止运行
如果进程中的所有线程全部终止运行(因为它们调用了E x i t T h r e a d 函数,或者因为它们已
经用Te r m i n a t e P r o c e s s 函数终止运行),操作系统就认为没有理由继续保留进程的地址空间。这
很好,因为在地址空间中没有任何线程执行任何代码。当系统发现没有任何线程仍在运行时,
它就终止进程的运行。出现这种情况时,进程的退出代码被设置为与终止运行的最后一个线程
相同的退出代码。