I am trying to implement a log file creation based on CRT debug tools, so far i have generated a simple file with some leaks on purpose just to see how it works.
#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;
}
Then i tried what i thought would be simple, create a file, grab the memory leak info and write to it, even CRT offers something called _CrtSetReportFile()
so i tried to implement something with it
#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;
}
The file is indeed generated but even though in my output i get memory leaks
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.
My file comes empty, what am i doing wrong or missing? Please Help
There are two problems in your code:
So you can change your code like this for example, using _get_osfhandle: