C ++中动态内存的生命周期 [英] Life time of Dynamic memory in C++

查看:84
本文介绍了C ++中动态内存的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我将内存动态分配给一个变量,如下所示,并假设我没有取消分配内存.然后它(分配的内存)将在系统中驻留多少时间.关闭应用程序时,它会释放内存吗?任何人都可以消除我的疑虑吗?

main()
{
int * ptr;
ptr = new sizeof(int);
}

Hi,

If I dynamically allocate memory to a variable as shown below and suppose that I am not deallocating the memory. Then how much time it(the allocated memory) will reside in the system. Will it release the memory when I close the application.? Can any one clear my doubts.?

main()
{
int *ptr;
ptr=new sizeof(int);
}

推荐答案

阿伦,我只想向C Pallini的正确答案添加注释.

即使您不必担心在应用程序终止时释放内存(它也会作为其他资源的 释放),但您仍应始终在每一步上释放堆内存.

一个明显的原因是防止内存泄漏( http://en.wikipedia.org/wiki/Memory_leak [^ ]).

另一个原因应该使您即使只分配一次内存的对象也要小心.实际上,释放内存失败不会影响应用程序的行为.但是,这将不利于代码的可维护性.后者可能由于任何原因而需要解决内存泄漏或使用某些内存调试器的情况;因此内存调试器将为您检测到误报,从而有效防止发现真正的"内存泄漏.

内存调试器可以成为您的好朋友,不要因糟糕或粗心的内存管理而出卖.关于内存调试器: http://en.wikipedia.org/wiki/Memory_debugger [
Arun, I just want to add a note to the correct answer by C Pallini.

Even though you should not worry about releasing of memory on application termination (it will also be released, as most of other resources), you should always release your heap memory on every step.

One obvious reason is preventing memory leaks (http://en.wikipedia.org/wiki/Memory_leak[^]).

Another reason should make you taking care even about the objects allocating memory only once. In practice, a failure to release memory would not affect the behavior of your application. However, it would be bad for maintainability of your code. It might happen that latter on you will need to fight a memory leak or use some memory debugger by any reasons; so the memory debugger will detect false positives for you, effectively preventing to find "real" memory leaks.

A memory debugger can be a dear friend to you, don''t betray it by lousy or careless memory management. About memory debuggers: http://en.wikipedia.org/wiki/Memory_debugger[^].

—SA


严格来说,它取决于操作系统. Windows和大多数(所有)Unix系统将在退出时清理该进程使用的内存.但是,在某些情况下它不会发生.
Strictly speaking, it depends on the OS. Windows and most (all?) Unix systems will clean up the memory used by the process when it exits. However, there are environments where it does not happen.


是的,它将保持分配状态,直到应用程序终止(关闭进程时,系统会清理"其资源) .
Yes, it will remain allocated until the application terminates (when the process is closed, the system ''cleans up'' its resources).


这篇关于C ++中动态内存的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆