应用程序突然关闭时的堆内存清除 [英] Heap memory clearance when application closes abruptly
问题描述
众所周知,堆用于为应用程序动态分配内存.在异常终止应用程序的情况下,如何清除堆内存(从而避免内存泄漏)?
As we know the heap is used for dynamic allocation of memory for an application. How is the heap memory cleared(and hence avoiding memory leaks) in case of abnormal application termination?
请考虑以下情形:
- 说一个应用程序在Windows或Linux上突然崩溃.
- 我们强制杀死linux中的应用程序:
kill -9 <process_name>
- Visual Studio中的C ++程序在执行过程中引发错误.
在上述情况下,堆管理和清理是否有所不同? [请添加更多可能在这里有用的用例场景]
Is heap management and cleanup any different in the above cases? [Please add more use-case scenarios which might be of interest here]
这个问题浮现在我的脑海,因为我们一直在谈论确保代码中不发生内存泄漏.现在,我们如何处理强制关闭应用程序而可能导致程序退出而又不调用内存释放调用的情况.
This question came up in my mind since we always talk about ensuring no memory leak happens in our code. Now how do we handle scenarios where we force close an application which might result into a program exit without calling the memory free-up calls.
并且如果这种内存泄漏反复发生,操作系统是否可能缺少堆内存?还是操作系统有一种处理方式...
And if such memory leak happens repeatedly, is it possible that the OS becomes short of heap memory? Or does the OS have a way of handling it...
推荐答案
As for dynamic memory management you should use RAII(smart pointers is one example) to take care of memory leaks and management during exceptions and so on.
In cases where your application exits, the OS simply reclaims back all the memory it gave to the process. The OS doesn't understand leaks, it simply takes back what it gave to a process. So there is no leak per se. All memory is reclaimed. You might leak other resources(file descriptors etc) but a clever use of RAII should guard you against that.
这篇关于应用程序突然关闭时的堆内存清除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!