new_delete.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef COMMON_HDFS_NEW_DELETE_H_
  19. #define COMMON_HDFS_NEW_DELETE_H_
  20. #include <cstring>
  21. struct mem_struct {
  22. size_t mem_size;
  23. };
  24. #ifndef NDEBUG
  25. #define MEMCHECKED_CLASS(clazz) \
  26. static void* operator new(size_t size) { \
  27. void* p = ::malloc(size); \
  28. return p; \
  29. } \
  30. static void* operator new[](size_t size) { \
  31. mem_struct* p = (mem_struct*)::malloc(sizeof(mem_struct) + size); \
  32. p->mem_size = size; \
  33. return (void*)++p; \
  34. } \
  35. static void operator delete(void* p) { \
  36. ::memset(p, 0, sizeof(clazz)); \
  37. ::free(p); \
  38. } \
  39. static void operator delete[](void* p) { \
  40. mem_struct* header = (mem_struct*)p; \
  41. size_t size = (--header)->mem_size; \
  42. ::memset(p, 0, size); \
  43. ::free(header); \
  44. }
  45. #else
  46. #define MEMCHECKED_CLASS(clazz)
  47. #endif
  48. #endif