CRT not creating correct output in UWP app

29 views Asked by At

I created a function that prints the _CrtDumpMemoryLeaks() into a file, i first tested my tentative approach in an empty c++ project, i set up some files , the test in this test project was good, i got my memory leaks printed into a file with a good format, no problem at all.

But when i try to apply that same functionality into a UWP(Universal Window Platform) app i am not getting the same results as within my test project, the file is generated but empty.

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); at the beginning of main but not showing the file and line

here is how my function looks

#include "MemoryLeakReporter.h"
#include <iostream>
#include <cstdio>

int MemoryLeakReporter::ReportMemoryLeak()
{

//Open the file for Writing
FILE* outfile = nullptr;
if (freopen_s(&outfile, "MemoryLeaksReport.log", "w", stdout) != 0 || outfile == nullptr)
{
    std::cerr << "Failed to open file for writing." << std::endl;
    return 1;
}



_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
// Trigger memory leak check
_CrtDumpMemoryLeaks();


return 0;

}

so far i have added in this main function the call to my function with Debug flags, something like this.

int WINAPI WinMain( HINSTANCE   ,
                HINSTANCE   ,
                LPSTR       lpCmdLine,
                int         )
{

#ifdef _DEBUG
   _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetBreakAlloc(206);
//Make the call here for MemoryLeakReporter
MemoryLeakReporter memoryLeakReporter;
memoryLeakReporter.ReportMemoryLeak();


#endif

}

i also tried added _CrtSetBreakAlloc to try and seee where exacty is happening but for some reason i don´t yet know the break does not happen, even though i tested it out on my Test_project and there it works as the doc suggests.

So i am kind of lost into exactly why the different behaviour

1

There are 1 answers

3
Tim Roberts On

This happens because a GUI app (meaning one which starts at WinMain, as opposed to a console app that starts at main) does not have a stdout. The run-time library closes those handles during startup, since it gives up the connection to a terminal. You just need to specify your own file handle instead of _CRTDBG_FILE_STDOUT.

Alternatively, for debugging purposes, you can replace the int WINAPI WinMain declaration with int main(). You can still open windows, but it will retain the connection to stdin and stdout.