为什么Xcode + Instrument Leaks在简单的C ++程序中没有检测到这个泄漏 [英] Why doesn't Xcode + Instrument Leaks detect this leak in simple C++ program

查看:297
本文介绍了为什么Xcode + Instrument Leaks在简单的C ++程序中没有检测到这个泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Xcode中的一个简单的C ++控制台项目中有以下内容。
当我使用instrument Leaks运行这个时,Xcode不会标记任何内存泄漏
,即使有一个明亮的。到底是怎么回事 ?任何帮助?

I have the following in a simple C++ console project in Xcode. When I run this with instrument Leaks, Xcode does not flag any memory leaks even thought there is a glaring one. What is going on ? Any help?

#include <iostream>

int main (int argc, char * const argv[]) {
    // insert code here...

    int *x = new int[20];
    x[0] = 10;
    std::cout << "Hello, World!\n";

    return 0;
}


推荐答案

。为了发生泄漏,您必须丢失必须分配内存的引用。在你的情况下,你不用分配的内存,但你仍然保留一个引用。因此,Leaks认为你可以潜在地稍后释放它,并且不认为它是泄漏。 (提醒一下,当你分配内存时,泄漏就是分配内存,然后处理指针而不释放内存。)

There's no leak in your code. For a leak to occur, you have to lose the reference you have to allocated memory. In your case, you do nothing more with the allocated memory, but you still keep a reference to it. Therefore, Leaks thinks you could potentially free it later at some point, and doesn't consider it a leak. (As a reminder, a leak is when you allocate memory, then dispose of the pointer without freeing the memory.)

这个程序应该让Leaks生气:

This program should make Leaks angry:

int main()
{
    int* foo = new int[10];
    foo = NULL;
    sleep(60);
}

正如你所看到的,<$ c $当 foo NULL 覆盖时,c> new int [10] 因此,Leaks应该发现它。

As you can see, the address of the memory returned by new int[10] is irremediably lost when foo is overwritten with NULL. Therefore, Leaks should spot it.

Leaks不是一个静态分析工具。它不知道你要用你的指针做什么。它所知道的是,每一块分配的内存仍然被引用某处。

Leaks is not a statical analysis tool. It doesn't know what you're gonna do with your pointers. All it knows is that every block of allocated memory is still referenced somewhere.

Leaks也不是一个实时工具。一旦发生泄漏,它不会发现泄漏。相反,每10秒钟左右,它会冻结程序,扫描其内存,并尝试查找对其分配的所有内存块的引用。如果它没有找到任何特定的块,它标记它为一个泄漏。因此,如果你的程序执行持续不到10秒,显然Leaks不会发现任何有用的。

Leaks is also not a real-time tool. It doesn't find leaks as soon as they occur. Instead, every 10 seconds or so, it freezes the program, scans its memory and tries to find references to all its allocated memory blocks. If it doesn't find any for a specific block, it flags it as a leak. Therefore, if your program's execution lasts less than 10 seconds, obviously Leaks won't find anything helpful.

这篇关于为什么Xcode + Instrument Leaks在简单的C ++程序中没有检测到这个泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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