Yos*_*fki 6 c c++ visual-studio-2010
我正在使用_CrtDumpMemoryLeaks运行良好的函数,但在文档中承诺不仅返回 true 或 false 还打印一些信息。
我尝试使用:
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );
Run Code Online (Sandbox Code Playgroud)
但我的一些代码在屏幕上没有出现。
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <stdio.h>
#include <string.h>
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;
}
Run Code Online (Sandbox Code Playgroud)
输出没有关于内存泄漏的数据......为什么会这样?
顺便说一下,输出是
是否有内存泄漏?: 1 按任意键继续。. .
我发现以下代码是最有用的,特别是当您开始将泄漏隔离到特定方法/函数时:
// declare memory stare variable
_CrtMemState state;
...
// create a checkpoint to for current memory state
_CrtMemCheckpoint(&state);
... do stuff ...
// report differences
_CrtMemDumpAllObjectsSince(&state);
Run Code Online (Sandbox Code Playgroud)
该例程将转储自检查点以来的所有分配。它可以围绕函数调用,在启动时和退出时加载等。我还在 DllMain 进程附加/分离的 DLL 中使用了它。
_CrtSetReportMode与、_CrtSetReportFile等组合时也很方便。
如果您在 Visual Studio 2010 调试实例中运行此程序,则需要查看调试输出(调试 -> Windows -> 输出)。
此外,您不仅需要设置错误的报告模式,还需要设置警告的报告模式(这是报告内存泄漏的地方):
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG );
/* Alternatively:
* _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
* _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
*/
Run Code Online (Sandbox Code Playgroud)
其中向我展示了您的程序的以下输出:
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
Run Code Online (Sandbox Code Playgroud)