对动态分配的对象调用 delete 是否总是内存泄漏? [英] Is not calling delete on a dynamically allocated object always a memory leak?

查看:25
本文介绍了对动态分配的对象调用 delete 是否总是内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从讨论开始这里,我想知道以下代码是否存在内存泄漏:>

From the discussion started here, I'd like to know whether the following code has a memory leak:

int main()
{
   new int();
   //or
   int* x = new int();
   return 0;
}

我知道内存已被操作系统回收,但这是否是泄漏?我相信是的.

I know the memory is reclaimed by the OS, but is it a leak anyway? I believe it is.

内存泄漏的定义是什么?我只能在标准中找到一个参考,而且不是很有帮助.

What defines a memory leak? I could only find one reference in the standard, and it wasn't very helpful.

我不想开始辩论——我认为……"不是我想要的那种答案.我最感兴趣的是来源 - 什么 C++ 书籍或网站或任何关于它的内容.

推荐答案

第二种情况不是内存泄漏.
这不是泄漏,因为您仍然有一个指向分配的内存的指针.
为了定义内存泄漏,我想坚持大多数内存分析工具(如 valgrind)使用的定义:

Second case is not a memory leak.
It is not a leak because you still have an pointer to the memory that was allocated.
To define a memory leak I would like to stick to definition which most of memory analysis tools like valgrind use:

内存已分配,随后无法释放,因为程序不再有任何指向已分配内存块的指针.

Memory was allocated and cannot be subsequently freed because the program no longer has any pointers to the allocated memory block.

这篇关于对动态分配的对象调用 delete 是否总是内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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