fork download
  1. #include <iostream>
  2. #include <map>
  3.  
  4. std::map<void*, std::size_t> memory; // globally allocated memory map
  5. struct tag {}; // tag for placement new's so we don't overload the global ones
  6.  
  7. void* operator new(std::size_t size, const tag&)
  8. {
  9. void* addr = malloc(size);
  10. memory[addr] = size;
  11. return addr;
  12. }
  13.  
  14. void* operator new[](std::size_t size, const tag&) // for arrays
  15. {
  16. return operator new(size, tag());
  17. }
  18.  
  19. void operator delete(void *p) noexcept
  20. {
  21. memory.erase(p);
  22. free(p);
  23. }
  24.  
  25. void operator delete[](void *p) noexcept // for arrays
  26. {
  27. operator delete(p);
  28. }
  29.  
  30. void display_memory()
  31. {
  32. std::cout << "Allocated heap memory: " << std::endl;
  33. for (auto && elem : memory)
  34. {
  35. std::cout << "\tADDR: " << elem.first << " "
  36. << "SIZE: " << elem.second << std::endl;
  37. }
  38. }
  39.  
  40. bool is_allocated(void* p)
  41. {
  42. return (memory.find(p) != memory.end());
  43. }
  44.  
  45. int main()
  46. {
  47. int *p = new(tag()) int[10];
  48. char *c = new(tag()) char;
  49.  
  50. // test if p is allocated
  51. std::cout << std::boolalpha << "Allocated: "
  52. << is_allocated(p) << std::endl;
  53.  
  54. // display the allocated memory
  55. display_memory();
  56.  
  57. // remove p
  58. delete[] p;
  59.  
  60. // test again if p is allocated
  61. std::cout << std::boolalpha << "Allocated: "
  62. << is_allocated(p) << std::endl;
  63.  
  64. display_memory();
  65.  
  66. // remove c
  67. delete c;
  68.  
  69. display_memory();
  70. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
Allocated: true
Allocated heap memory: 
	ADDR: 0x875e008 SIZE: 40
	ADDR: 0x875e058 SIZE: 1
Allocated: false
Allocated heap memory: 
	ADDR: 0x875e058 SIZE: 1
Allocated heap memory: