Advertisement
bueddl

operator new overload

May 30th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <new>
  3. #include <iomanip>
  4. #include <malloc.h>
  5.  
  6. #ifdef _DEBUG
  7. void* _perform_alloc(std::size_t count)
  8. {
  9.     std::cout << "[DEBUG] Allocating "
  10.                         << std::dec << count
  11.                         << " bytes of heap memory" << std::endl;
  12.  
  13.     void *ptr = malloc(count);
  14.  
  15.     if (!ptr) {
  16.         std::cerr << "[DEBUG] Allocation failed" << std::endl;
  17.         throw std::bad_alloc();
  18.     }
  19.  
  20.     std::cout << "[DEBUG] Allocated at "
  21.                         << std::showbase << std::hex << ptr
  22.                         << std::endl;
  23.     return ptr;
  24. }
  25.  
  26. void* operator new(std::size_t count)
  27. {
  28.     return _perform_alloc(count);
  29. }
  30.  
  31. void* operator new[](std::size_t count)
  32. {
  33.     return _perform_alloc(count);
  34. }
  35. #endif
  36.  
  37. int main()
  38. {
  39.     int *t1 = new int;
  40.  
  41.     int *t2 = new int[20];
  42.  
  43.     double *t3 = new double[2000000000]; // This really should fail
  44.  
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement