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
15 /*
16 void * my_new(size_t size)
17 {
18 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size);
19 void *p = ::malloc(size);
20 if (p == 0)
21 throw CNewException();
22 return p;
23 }
24
25 void my_delete(void *p) throw()
26 {
27 // if (p == 0) return; ::HeapFree(::GetProcessHeap(), 0, p);
28 ::free(p);
29 }
30
31 void * my_Realloc(void *p, size_t newSize, size_t oldSize)
32 {
33 void *newBuf = my_new(newSize);
34 if (oldSize != 0)
35 memcpy(newBuf, p, oldSize);
36 my_delete(p);
37 return newBuf;
38 }
39 */
40
41 void *
42 #ifdef _MSC_VER
43 __cdecl
44 #endif
operator new(size_t size)45 operator new(size_t size)
46 {
47 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size);
48 void *p = ::malloc(size);
49 if (p == 0)
50 throw CNewException();
51 return p;
52 }
53
54 void
55 #ifdef _MSC_VER
56 __cdecl
57 #endif
operator delete(void * p)58 operator delete(void *p) throw()
59 {
60 // if (p == 0) return; ::HeapFree(::GetProcessHeap(), 0, p);
61 ::free(p);
62 }
63
64 /*
65 void *
66 #ifdef _MSC_VER
67 __cdecl
68 #endif
69 operator new[](size_t size)
70 {
71 // void *p = ::HeapAlloc(::GetProcessHeap(), 0, size);
72 void *p = ::malloc(size);
73 if (p == 0)
74 throw CNewException();
75 return p;
76 }
77
78 void
79 #ifdef _MSC_VER
80 __cdecl
81 #endif
82 operator delete[](void *p) throw()
83 {
84 // if (p == 0) return; ::HeapFree(::GetProcessHeap(), 0, p);
85 ::free(p);
86 }
87 */
88
89 #endif
90
91 #else
92
93 #include <stdio.h>
94
95 // #pragma init_seg(lib)
96 const int kDebugSize = 1000000;
97 static void *a[kDebugSize];
98 static int index = 0;
99
100 static int numAllocs = 0;
operator new(size_t size)101 void * __cdecl operator new(size_t size)
102 {
103 numAllocs++;
104 void *p = HeapAlloc(GetProcessHeap(), 0, size);
105 if (index < kDebugSize)
106 {
107 a[index] = p;
108 index++;
109 }
110 if (p == 0)
111 throw CNewException();
112 printf("Alloc %6d, size = %8u\n", numAllocs, (unsigned)size);
113 return p;
114 }
115
116 class CC
117 {
118 public:
CC()119 CC()
120 {
121 for (int i = 0; i < kDebugSize; i++)
122 a[i] = 0;
123 }
~CC()124 ~CC()
125 {
126 for (int i = 0; i < kDebugSize; i++)
127 if (a[i] != 0)
128 return;
129 }
130 } g_CC;
131
132
operator delete(void * p)133 void __cdecl operator delete(void *p)
134 {
135 if (p == 0)
136 return;
137 /*
138 for (int i = 0; i < index; i++)
139 if (a[i] == p)
140 a[i] = 0;
141 */
142 HeapFree(GetProcessHeap(), 0, p);
143 numAllocs--;
144 printf("Free %d\n", numAllocs);
145 }
146
147 #endif
148
149 /*
150 int MemErrorVC(size_t)
151 {
152 throw CNewException();
153 // return 1;
154 }
155 CNewHandlerSetter::CNewHandlerSetter()
156 {
157 // MemErrorOldVCFunction = _set_new_handler(MemErrorVC);
158 }
159 CNewHandlerSetter::~CNewHandlerSetter()
160 {
161 // _set_new_handler(MemErrorOldVCFunction);
162 }
163 */
164