NewHandler.cpp 1.7 KB

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