DebugMemoryLeakCheck.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* Copyright The kNet Project.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License. */
  11. #pragma once
  12. /** @file DebugMemoryLeakCheck.h
  13. @brief Provides overloads of operators new and delete for tracking memory leaks. */
  14. // Modified by Lasse Oorni for Urho3D
  15. // Urho3D: only include on MSVC
  16. #if defined(_MSC_VER) && defined(_DEBUG) && defined(KNET_MEMORY_LEAK_CHECK)
  17. #include <new>
  18. #include <crtdbg.h>
  19. // On MSVC2008, include these files beforehand to avoid compilation errors from our operator new redefine.
  20. #if _MSC_VER == 1500
  21. #include <ios>
  22. #include <map>
  23. #endif
  24. #ifndef _CRTDBG_MAP_ALLOC
  25. #define _CRTDBG_MAP_ALLOC
  26. #endif
  27. __forceinline static void *operator new(size_t size, const char *file, int line)
  28. {
  29. return _malloc_dbg(size, _NORMAL_BLOCK, file, line);
  30. }
  31. __forceinline static void *operator new[](size_t size, const char *file, int line)
  32. {
  33. return _malloc_dbg(size, _NORMAL_BLOCK, file, line);
  34. }
  35. __forceinline static void operator delete(void *ptr, const char *, int)
  36. {
  37. _free_dbg(ptr, _NORMAL_BLOCK);
  38. }
  39. __forceinline static void operator delete[](void *ptr, const char *, int)
  40. {
  41. _free_dbg(ptr, _NORMAL_BLOCK);
  42. }
  43. __forceinline void *operator new(size_t size)
  44. {
  45. #ifdef DEBUG_CPP_NAME
  46. return _malloc_dbg(size, _NORMAL_BLOCK, DEBUG_CPP_NAME, 1);
  47. #else
  48. return _malloc_dbg(size, _NORMAL_BLOCK, "(No CPP Name)", 1);
  49. #endif
  50. }
  51. __forceinline void *operator new[](size_t size)
  52. {
  53. #ifdef DEBUG_CPP_NAME
  54. return _malloc_dbg(size, _NORMAL_BLOCK, DEBUG_CPP_NAME " new[]", 1);
  55. #else
  56. return _malloc_dbg(size, _NORMAL_BLOCK, "(No CPP Name new[])", 1);
  57. #endif
  58. }
  59. __forceinline void operator delete(void *ptr)
  60. {
  61. _free_dbg(ptr, _NORMAL_BLOCK);
  62. }
  63. __forceinline void operator delete[](void *ptr)
  64. {
  65. _free_dbg(ptr, _NORMAL_BLOCK);
  66. }
  67. #define new new (__FILE__, __LINE__)
  68. #endif