【问题标题】:C++ Program with Perfomance Tool - Leaks带有性能工具的 C++ 程序 - 泄漏
【发布时间】:2011-03-24 04:51:37
【问题描述】:
int main (int argc, char * const argv[])
{
    int *num = new int[100] ;
    return 0;
}

在上面的程序中,肯定存在内存泄漏。但是当 Run -> Run with Performance Tool -> Leaks 时,会给出下图,显示没有泄漏的对象。我错过了什么?性能工具是否仅适用于 Objective C 环境?

编辑:

在 MSVC++ 2010 上,在调试模式下运行时很容易检测到泄漏 -

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

int main (int argc, char * const argv[])
{
    int *num = new int[100] ;

    _CrtDumpMemoryLeaks();   // Looking for something equivalent to this
                             // that lets me know whether the program has
                             // memory leaks on an XCode environment.

    return 0;
}

【问题讨论】:

  • 您正在以完全优化的方式运行?
  • @Naveen - 我在调试模式下运行,但不确定完全优化。会检查的。
  • @Naveen - 优化级别 -> 无。
  • 如果它经过优化,我可以看到编译器只是扔掉了 new 语句。
  • 不是很相关,但似乎有一些 Valgrind 端口到 Mac:sealiesoftware.com/valgrind

标签: c++ performance memory-leaks xcode3.2


【解决方案1】:

leaks 不会对未释放的块执行事后转储。

相反,它会在进程运行时分析进程并查找不再可访问的已分配块。它按需或每 10 秒扫描一次。

将您的程序更改为以下内容:

int main (int argc, char * const argv[]) 
{
    int *num = new int[100] ;
    char c;

    puts("memory allocated\npress a key to continue...\n");
    c = getchar();

    num = NULL; // leak the allocation

    puts("memory has been leaked\npress a key to continue...\n");
    c = getchar();

    return 0; 
}

如果您在程序等待第二次按键时进行扫描,它应该会检测到泄漏。

【讨论】:

猜你喜欢
  • 2011-11-26
  • 1970-01-01
  • 2010-11-10
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多