Advertisement
Ginsutime

Track Memory Allocations Cherno

Feb 16th, 2022
1,041
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <memory>
  4.  
  5. struct AllocationMetrics
  6. {
  7.     uint32_t TotalAllocated = 0;
  8.     uint32_t TotalFreed = 0;
  9.  
  10.     uint32_t CurrentUsage() { return TotalAllocated - TotalFreed; }
  11. };
  12.  
  13. static AllocationMetrics s_AllocationMetrics;
  14.  
  15. void* operator new(size_t size)
  16. {
  17.     s_AllocationMetrics.TotalAllocated += size;
  18.  
  19.     // Allocate appropriate amount of memory to us and then return a pointer to that memory
  20.     return malloc(size);
  21. }
  22.  
  23. void operator delete(void* memory, size_t size)
  24. {
  25.     s_AllocationMetrics.TotalFreed += size;
  26.  
  27.     free(memory);
  28. }
  29.  
  30. struct Object
  31. {
  32.     int x, y, z;
  33. };
  34.  
  35. static void PrintMemoryUsage()
  36. {
  37.     std::cout << "Memory Usage: " << s_AllocationMetrics.CurrentUsage() << " bytes\n";
  38. }
  39.  
  40. int main()
  41. {
  42.     PrintMemoryUsage();
  43.     std::string string = "Cherno";
  44.     PrintMemoryUsage();
  45.     {
  46.         std::unique_ptr<Object> obj = std::make_unique<Object>();
  47.         PrintMemoryUsage();
  48.     }
  49.     PrintMemoryUsage();
  50.  
  51.     //Object* obj = new Object;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement