1 // NewHandler.cpp 2 3 #include "StdAfx.h" 4 5 #include <stdlib.h> 6 7 #include "NewHandler.h" 8 9 // #define DEBUG_MEMORY_LEAK 10 11 #ifndef DEBUG_MEMORY_LEAK 12 13 #ifdef _WIN32 14 void * 15 #ifdef _MSC_VER 16 __cdecl 17 #endif 18 operator new(size_t size) 19 { 20 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size); 21 void *p = ::malloc(size); 22 if (p == 0) 23 throw CNewException(); 24 return p; 25 } 26 27 void 28 #ifdef _MSC_VER 29 __cdecl 30 #endif 31 operator delete(void *p) throw() 32 { 33 /* 34 if (p == 0) 35 return; 36 ::HeapFree(::GetProcessHeap(), 0, p); 37 */ 38 ::free(p); 39 } 40 #endif 41 42 #else 43 44 #pragma init_seg(lib) 45 const int kDebugSize = 1000000; 46 static void *a[kDebugSize]; 47 static int index = 0; 48 49 static int numAllocs = 0; 50 void * __cdecl operator new(size_t size) 51 { 52 numAllocs++; 53 void *p = HeapAlloc(GetProcessHeap(), 0, size); 54 if (index == 40) 55 { 56 int t = 1; 57 } 58 if (index < kDebugSize) 59 { 60 a[index] = p; 61 index++; 62 } 63 if (p == 0) 64 throw CNewException(); 65 printf("Alloc %6d, size = %8d\n", numAllocs, size); 66 return p; 67 } 68 69 class CC 70 { 71 public: 72 CC() 73 { 74 for (int i = 0; i < kDebugSize; i++) 75 a[i] = 0; 76 } 77 ~CC() 78 { 79 for (int i = 0; i < kDebugSize; i++) 80 if (a[i] != 0) 81 return; 82 } 83 } g_CC; 84 85 86 void __cdecl operator delete(void *p) 87 { 88 if (p == 0) 89 return; 90 /* 91 for (int i = 0; i < index; i++) 92 if (a[i] == p) 93 a[i] = 0; 94 */ 95 HeapFree(GetProcessHeap(), 0, p); 96 numAllocs--; 97 printf("Free %d\n", numAllocs); 98 } 99 100 #endif 101 102 /* 103 int MemErrorVC(size_t) 104 { 105 throw CNewException(); 106 // return 1; 107 } 108 CNewHandlerSetter::CNewHandlerSetter() 109 { 110 // MemErrorOldVCFunction = _set_new_handler(MemErrorVC); 111 } 112 CNewHandlerSetter::~CNewHandlerSetter() 113 { 114 // _set_new_handler(MemErrorOldVCFunction); 115 } 116 */ 117