Advertisement
kevkul

operator new

May 7th, 2020
1,041
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.73 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <new>
  3. #include <memory>
  4.  
  5. static const auto max_align_s = sizeof(std::max_align_t);
  6.  
  7. void* operator new(size_t size) {
  8.     void* p = std::malloc(size + max_align_s);
  9.     if (p == nullptr) {
  10.         throw std::bad_alloc{};
  11.     }
  12.  
  13.     char* begin = static_cast<char*>(p) + max_align_s;
  14.     char* end = begin + size;
  15.  
  16.     std::uninitialized_fill(begin, end, 0x00);
  17.  
  18.     new (p) int64_t{ size };
  19.  
  20.     return begin;
  21. }
  22.  
  23. void operator delete(void* p) {
  24.     if (p == nullptr) {
  25.         return;
  26.     }
  27.  
  28.     char* c = static_cast<char*>(p) - max_align_s;
  29.  
  30.     const uint64_t size = *reinterpret_cast<uint64_t*>(c);
  31.  
  32.     char* begin = static_cast<char*>(p);
  33.     char* end = begin + size;
  34.     std::uninitialized_fill(begin, end, 0xff);
  35.  
  36.     std::free(c);
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement