debugnew
debugnew
debugnew.h
#ifdef _DEBUG
#ifndef __DEBUG_NEW_H
#define __DEBUG_NEW_H
#define THIS_FILE __FILE__
void* __cdecl operator new(size_t nSize, int nType, const char* lpszFileName, int nLine);
void* _cdecl operator new(size_t nSize, const char* lpszFileName, int nLine);
void* __cdecl operator new[](size_t nSize, const char* lpszFileName, int nLine);
void __cdecl operator delete(void* p);
void __cdecl operator delete[](void* p);
#define DEBUG_NEW new(THIS_FILE, __LINE__)
#endif //__DEBUG_NEW_H
#endif // _DEBUG
debugnew.cpp
#ifdef _DEBUG
#include <crtdbg.h>
#include "../include/debugnew.h"
namespace
{
class AutoDetectMemory
{
public:
AutoDetectMemory()
{
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
}
};
static AutoDetectMemory gs_am;
}
void* _cdecl operator new(size_t nSize, const char* lpszFileName, int nLine)
{
return ::operator new(nSize, _NORMAL_BLOCK, lpszFileName, nLine);
}
void* __cdecl operator new[](size_t nSize, const char* lpszFileName, int nLine)
{
return ::operator new(nSize, _NORMAL_BLOCK, lpszFileName, nLine);
}
void __cdecl operator delete(void* p)
{
_free_dbg(p, _NORMAL_BLOCK);
}
void __cdecl operator delete[](void* p)
{
::operator delete(p);
}
void* __cdecl operator new(size_t nSize, int nType, const char* lpszFileName, int nLine)
{
return _malloc_dbg(nSize, nType, lpszFileName, nLine);
}
#endif // _DEBUG
main.cpp
#include "debugnew.h"
#include <iostream>
using namespace std;
class CTest
{
public:
int a;
int b;
};
int main()
{
int* p1 = new int;
char* p2 = new char[10];
delete p1;
delete[] p2;
CTest *p = new CTest;
//delete p;
system("pause");
return 0;
}
輸出結果
Detected memory leaks!
Dumping objects ->
{63} normal block at 0x00B61A98, 8 bytes long.
Data: < > CD CD CD CD CD CD CD CD
Object dump complete.
main.cpp
#include "debugnew.h"
#include <iostream>
using namespace std;
class CTest
{
public:
int a;
int b;
};
int main()
{
_CrtSetBreakAlloc(63); //加入這個
int* p1 = new int;
char* p2 = new char[10];
delete p1;
delete[] p2;
CTest *p = new CTest;
//delete p;
system("pause");
return 0;
}
參考網站
https://docs.microsoft.com/zh-tw/visualstudio/debugger/finding-memory-leaks-using-the-crt-library?view=vs-2019
https://www.codenong.com/cs106930305/
http://www.cppblog.com/Robertxiao/archive/2012/11/05/194547.html
http://wiki.jostudio.net/programmingnote:c:memoryleak
留言
張貼留言