我正在尝试基于CRT调试工具实现日志文件创建,到目前为止我已经生成了一个带有一些泄漏的简单文件,只是为了看看它是如何工作的。
#include "OtherSource.h"
#include <iostream>
#include <stdio.h>
int Simulation::SimulateLeak()
{
#ifdef _DEBUG
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
int* offset_x = DBG_NEW int;
int* offset_y = DBG_NEW int;
if (offset_x == NULL || offset_y == NULL) {
return 1;
}
*offset_x = 10;
*offset_y = 20;
delete offset_x;
#ifdef _DEBUG
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
_CrtDumpMemoryLeaks();
#endif
return 0;
}
然后我尝试了我认为很简单的方法,创建一个文件,抓取内存泄漏信息并写入它,甚至 CRT 也提供了名为 _CrtSetReportFile()
的东西所以我尝试用它来实现一些东西
#include "OtherSource.h"
#include <iostream>
#include <stdio.h>
int Simulation::SimulateLeak()
{
#ifdef _DEBUG
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
// Set the file where the report should go
FILE* leakReportFile = fopen("MemoryLeakReport.txt", "w");
_CrtSetReportFile(_CRT_WARN, leakReportFile);
int* offset_x = DBG_NEW int;
int* offset_y = DBG_NEW int;
if (offset_x == NULL || offset_y == NULL) {
return 1;
}
*offset_x = 10;
*offset_y = 20;
delete offset_x;
#ifdef _DEBUG
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
_CrtDumpMemoryLeaks();
#endif
// Close the file after dumping memory leaks
fclose(leakReportFile);
return 0;
}
文件确实已生成,但即使在我的输出中我遇到内存泄漏
Detected memory leaks!
Dumping objects ->
C:\C++\CRTDebugTest\CRTDebugTest\Source.cpp(10) : {183} normal block at 0x000002CEAFE21FF0, 4 bytes long.
Data: <( > 28 00 00 00
C:\C++\CRTDebugTest\CRTDebugTest\OtherSource.cpp(29) : {181} normal block at 0x000002CEAFE22570, 4 bytes long.
Data: < > 14 00 00 00
C:\C++\CRTDebugTest\CRTDebugTest\OtherSource.cpp(28) : {180} normal block at 0x000002CEAFE21BF0, 4 bytes long.
Data: < > 0A 00 00 00
Object dump complete.
我的文件为空,我做错了什么或遗漏了什么?请帮忙
您的代码中有两个问题:
因此您可以像这样更改代码,例如使用 _get_osfhandle:
// Set the file where the report should go
FILE* leakReportFile = fopen("MemoryLeakReport.txt", "w");
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, (void*)_get_osfhandle(_fileno(leakReportFile)));