How to detect
memory leaks and other memory errors in Visual C++:
First, make the following changes to your Project Settings (select Project -> Settings... from the
menu):
WIN32,_DEBUG,_CONSOLE,_MBCS,_AFXDLL
(You will most likely need to add _AFXDLL to the end).
#include <afx.h>
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include <string>
#include <iostream>
Notes:
Feihong Hsu
fhsu@cs.uic.edu
April 21, 2003
-----------------------------------------------------------------------------------------------
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
#include <afx.h>
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// Some helpful but not entirely necessary macros:
// Tweak the behavior of the debug heap:
#define SetDebugFlags \
int tmpFlag = _CrtSetDbgFlag(
_CRTDBG_REPORT_FLAG ); \
tmpFlag |=
_CRTDBG_CHECK_ALWAYS_DF; \
tmpFlag |=
_CRTDBG_LEAK_CHECK_DF; \
_CrtSetDbgFlag( tmpFlag );
// Send all memory error reports to stdout instead of the Output window:
#define SendReportsToStdout \
_CrtSetReportMode( _CRT_WARN,
_CRTDBG_MODE_FILE ); \
_CrtSetReportFile( _CRT_WARN,
_CRTDBG_FILE_STDOUT ); \
_CrtSetReportMode(
_CRT_ERROR, _CRTDBG_MODE_FILE ); \
_CrtSetReportFile(
_CRT_ERROR, _CRTDBG_FILE_STDOUT ); \
_CrtSetReportMode(
_CRT_ASSERT, _CRTDBG_MODE_FILE ); \
_CrtSetReportFile(
_CRT_ASSERT, _CRTDBG_FILE_STDOUT );
int main()
{
int* intArray = new int[45];
intArray[4] = 56;
intArray[44] = 322;
intArray[45] = 4342; // oops, corrupted the memory!
intArray[-1] = 31; // oops, did it again!
// _CrtCheckMemory(); // set
a breakpoint, or else just wrap an assert around it
delete[] intArray;
return 0;
}