c++ - XCode 未显示 C++ 程序中的泄漏

标签 c++ xcode memory-leaks instruments xcode-instruments

我用 c++ 编写了以下代码作为 xcode 命令行工具

int * num = new int[100];

num[4] = 5;
num = NULL;

cout << "leaked" << endl;

string c; cin >> c;

return 0;

然而,当使用带有 Leaks 模板的 Instruments 进行分析时,它没有显示任何内存泄漏,尽管在等待输入时显然应该存在内存泄漏。 enter image description here

最佳答案

当您为分析进行编译时,编译器会进行优化。其中一项优化是 dead-store 优化:

num = NULL; // The optimizer deleted this operation

通常,您为什么要关心 num 是否真的等于 NULL?由于您从未读取过 num 的值,因此如果不查看汇编输出,您就无法知道编译器是否实际将 NULL 存储在那里。因此,编译器实际上不会将 NULL 写入该位置。

等等,还有更多

我做了一个测试:

#include <unistd.h>
int main()
{
    int *num = new int[100];
    num[4] = 5;
    num = NULL;
    sleep(1);
    return 0;
}

程序集(为简洁起见省略序言和结语):

movl    $1, %edi
callq   _sleep
xorl    %eax, %eax

等一下,new int[100]num[4] = 5 发生了什么?

整个分配得到了优化,因为编译器找到了一种无需分配任何东西即可获得相同结果的方法。编译器很棒,不是吗?

关于c++ - XCode 未显示 C++ 程序中的泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152476/

相关文章:

ios - Xcode 单元测试缺少某些项目类

ios - reloadData 不调用 cellForItemAt

c++ - 供应商是否将 new 和 malloc 实现为小对象分配器?

c++ - 在 c++ 中传递时对象重置

C++ stoi 超出范围问题

swift - 如何将特定内容从 Collection View 添加到另一个 Collection View ?

android - 在 Eclipse MAT 中,类(class)末尾的美元符号是什么意思?

java - 在 Java 应用程序中使用 JAXBContext 解决内存泄漏

c++ - 使用 Windbg 分析转储文件中可能存在的内存泄漏

c++ - 通过 RInside 运行时 abline 出错