使用_CrtDumpMemoryLeaks将数据显示到控制台

我正在使用_CrtDumpMemoryLeaks函数,它工作正常但在文档中承诺不仅要返回true或false,还要打印一些信息。

我试过用:

 _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG ); 

但是这里的一些代码没有出现在屏幕上。

 #define _CRTDBG_MAP_ALLOC #include  #include  #include  #include  int main() { slist* students = 0; clist* courses = 0; char c; char buf[100]; int id, num; malloc(100); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG ); printf("there is memmory leaks?: %d\n",_CrtDumpMemoryLeaks()); system("pause"); return 0; } 

输出没有关于内存泄漏的数据..为什么会这样?

顺便说一下输出

有memory leaks?:1按任意键继续。 。 。

如果您在Visual Studio 2010调试实例中运行此操作,则需要查看调试输出(调试 – > Windows – >输出)。

此外,您不仅需要为错误设置报告模式, 还需要为警告设置报告模式(这将报告内存泄漏):

 _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG ); /* Alternatively: * _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE ); * _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR ); */ 

其中为我的程序提供了以下输出:

 Detected memory leaks! Dumping objects -> dump.c(14) : {86} normal block at 0x00834E50, 100 bytes long. Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD Object dump complete. there is memmory leaks?: 1 

我发现以下代码是最有用的,特别是当您开始将泄漏隔离到特定的方法/函数时:

 // declare memory stare variable _CrtMemState state; ... // create a checkpoint to for current memory state _CrtMemCheckpoint(&state); ... do stuff ... // report differences _CrtMemDumpAllObjectsSince(&state); 

此例程将转储自检查点以来的所有分配。 IT可以围绕一个函数调用,在启动时和退出时加载等。我也在DllMain进程附加/分离的DLL中使用它。

_CrtSetReportMode_CrtSetReportFile等结合使用时也很方便