NewHandler.cpp revision baa3858d3f5d128a5c8466b700098109edcad5f2
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
14void *
15#ifdef _MSC_VER
16__cdecl
17#endif
18operator 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
27void
28#ifdef _MSC_VER
29__cdecl
30#endif
31operator 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)
45const int kDebugSize = 1000000;
46static void *a[kDebugSize];
47static int index = 0;
48
49static int numAllocs = 0;
50void * __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
69class CC
70{
71public:
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
86void __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/*
103int MemErrorVC(size_t)
104{
105  throw CNewException();
106  // return 1;
107}
108CNewHandlerSetter::CNewHandlerSetter()
109{
110  // MemErrorOldVCFunction = _set_new_handler(MemErrorVC);
111}
112CNewHandlerSetter::~CNewHandlerSetter()
113{
114  // _set_new_handler(MemErrorOldVCFunction);
115}
116*/
117