寫c++程序時,經常會出現內存洩漏的問題,這裡從網上找了一種很麻煩的方法:如果想找到每個cpp文件的內存洩漏,都必須在每個cpp加上如下代碼:
#include#ifdef _DEBUG #define DEBUG_CLIENTBLOCK new(_CLIENT_BLOCK, __FILE__, __LINE__) #define new DEBUG_CLIENTBLOCK #else #define DEBUG_CLIENTBLOCK #endif
下面給出一段測試的代碼
test.h
#includetest.cppvoid funNew();
#include "text.h" #includemain.cpp#ifdef _DEBUG #define DEBUG_CLIENTBLOCK new(_CLIENT_BLOCK, __FILE__, __LINE__) #define new DEBUG_CLIENTBLOCK #else #define DEBUG_CLIENTBLOCK #endif void funNew() { int *p = new int(); }
#include#include #include "text.h" #include #ifdef _DEBUG #define DEBUG_CLIENTBLOCK new(_CLIENT_BLOCK, __FILE__, __LINE__) #define new DEBUG_CLIENTBLOCK #else #define DEBUG_CLIENTBLOCK #endif int main() { _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); int* p = new int(); funNew(); //delete p; return 0; }
Detected memory leaks! Dumping objects -> f:\project1\test.cpp(13) : {157} client block at 0x001E9180, subtype 0, 4 bytes long. Data: < > 00 00 00 00 f:\project1\main.cpp(17) : {156} client block at 0x001E9140, subtype 0, 4 bytes long. Data: < > 00 00 00 00 Object dump complete.