c++newオペレータをリロードし、メモリの漏洩を防止
13399 ワード
c++開発の過程で、メモリ漏洩はプログラマーを最も悩ませることであり、メモリ漏洩の場所を見つけるために長い間デバッグすることがある.newオペレータを再ロードすることは、多くの大規模なプロジェクトでよく使われるメモリ漏洩防止の手段です.私は暇で、newオペレータのリロード関数を書いて、みんなはお互いに勉強して、足りないところがあって、みんなに指摘してもらいたいです.
コードをつけると、あまり説明しません.
最終的な実行結果は次のとおりです.
c:\c++\test\test\main.cpp : LINE 6, ADDRESS 6637816 5 unfreed ----------------------------------------------------------- Total Unfreed: 5 bytes
一部のコンパイラでは、warning C 4291:「void*operator new(unsigned int,const char*,int)」:一致する削除演算子が見つかりません.初期化によって例外が発生した場合、メモリは解放されません.
このエラーを防止するには、2つのdeleteメソッドを定義します.次のようになります.
コードをつけると、あまり説明しません.
1 #ifndef _BASE_H_
2 #define _BASE_H_
3
4 #include
5 #include
6 #include
1 #include "base.h"
2 #define new DEBUG_NEW
3
4 int main()
5 {
6 char* pszCeshi = new char[5];
7 DumpUnfreed();
8 return 0;
9 }
最終的な実行結果は次のとおりです.
c:\c++\test\test\main.cpp : LINE 6, ADDRESS 6637816 5 unfreed ----------------------------------------------------------- Total Unfreed: 5 bytes
一部のコンパイラでは、warning C 4291:「void*operator new(unsigned int,const char*,int)」:一致する削除演算子が見つかりません.初期化によって例外が発生した場合、メモリは解放されません.
このエラーを防止するには、2つのdeleteメソッドを定義します.次のようになります.
inline void operator delete(void *p , const char *file, int line)
{
RemoveTrack((unsigned long)p);
free(p);
}
inline void operator delete[](void *p, const char *file, int line)
{
RemoveTrack((unsigned long)p);
free(p);
}