メモリリークに関する情報を出力することになっているプログラムがあります。しかし、それは機能していません。プログラムは次のとおりです。
#include <crtdbg.h>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
FILE *out_file;
int *a = new int;
//Redirect the error stream to a file.
freopen_s (&out_file, "Memory Leaks.txt", "w", stderr);
//Turn on debugging for memory leaks. This is automatically turned off when the build is Release.
_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode (_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile (_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode (_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile (_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportMode (_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile (_CRT_ASSERT, _CRTDBG_FILE_STDERR);
return 0;
}
私は DEBUG バージョンでビルドしているので、関数は無視されるべきではありません。私が使用しているコンパイラはVisual Studio 2010です。プログラムはファイル「Memory Leaks.txt」を作成するだけで、ファイルにはコンテンツがありません。何かご意見は?
- 編集 -
提案どおり「適切なファイル ハンドル」を使用するようにプログラムを更新しました。プログラムはまだファイルに何も出力しません。
- 編集 -
問題は、ファイルを閉じることでした。次のコードが機能するようになりました。
#include <crtdbg.h>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
HANDLE hLogFile;
int *a;
//Open a file for output.
hLogFile = CreateFile ("Memory Leaks.txt", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
//Turn on debugging for memory leaks. This is automatically turned off when the build is Release.
_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode (_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile (_CRT_WARN, hLogFile);
_CrtSetReportMode (_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile (_CRT_ERROR, hLogFile);
_CrtSetReportMode (_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile (_CRT_ASSERT, hLogFile);
//Create a memory leak.
a = new int;
//Don't close this file. Closing the file will cause the report not to be outputted.
//CloseHandle(hLogFile);
return 0;
}