fork download
  1. #include <iostream>
  2. #include <cstdint>
  3. using namespace std;
  4.  
  5. void* operator new( size_t size )
  6. {
  7. std::cout << "The size 'new' is actually asking for: " << size << " bytes." << std::endl;
  8. void* memory = malloc( size ); // Let's say the pointer was 4
  9.  
  10. std::cout << "Original address: " << memory << std::endl;
  11.  
  12. return memory; // Pointer is still 4
  13. }
  14.  
  15. class Object
  16. {
  17. public:
  18. Object() = default;
  19. virtual ~Object() = default; //Virtual, to give it a vtable, to ensure it's non-POD.
  20.  
  21. int meow = 357;
  22. };
  23.  
  24. struct POD
  25. {
  26. uint64_t A;
  27. uint64_t B;
  28. };
  29.  
  30. int main()
  31. {
  32. const int NumObjectsToAllocate = 4;
  33. std::cout << "Sizeof 'Object': " << sizeof(Object) << std::endl;
  34. std::cout << "Allocating " << NumObjectsToAllocate
  35. << " Objects should take " << (NumObjectsToAllocate * sizeof(Object))
  36. << " bytes." << std::endl;
  37.  
  38. Object *stuff = new Object[ NumObjectsToAllocate ];
  39.  
  40. std::cout << "Resulting address: " << stuff << std::endl;
  41.  
  42. delete[] stuff;
  43.  
  44. std::cout << "---------------------------------------" << std::endl;
  45.  
  46. const int NumOfFloatsToAllocate = 4;
  47. std::cout << "Sizeof 'float': " << sizeof(float) << std::endl;
  48. std::cout << "Allocating " << NumOfFloatsToAllocate
  49. << " floats should take " << (NumOfFloatsToAllocate * sizeof(float))
  50. << " bytes." << std::endl;
  51.  
  52. float *floats = new float[ NumOfFloatsToAllocate ];
  53.  
  54. std::cout << "Resulting address: " << floats << std::endl;
  55.  
  56. delete[] floats;
  57.  
  58. std::cout << "---------------------------------------" << std::endl;
  59.  
  60. const int NumOfPodsToAllocate = 4;
  61. std::cout << "Sizeof 'Pod': " << sizeof(POD) << std::endl;
  62. std::cout << "Allocating " << NumOfPodsToAllocate
  63. << " pods should take " << (NumOfPodsToAllocate * sizeof(POD))
  64. << " bytes." << std::endl;
  65.  
  66. POD *pods = new POD[ NumOfPodsToAllocate ];
  67.  
  68. std::cout << "Resulting address: " << pods << std::endl;
  69.  
  70. delete[] pods;
  71.  
  72. return 0;
  73. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Sizeof 'Object': 8
Allocating 4 Objects should take 32 bytes.
The size 'new' is actually asking for: 36 bytes.
Original address: 0x9f54008
Resulting address: 0x9f5400c
---------------------------------------
Sizeof 'float': 4
Allocating 4 floats should take 16 bytes.
The size 'new' is actually asking for: 16 bytes.
Original address: 0x9f54030
Resulting address: 0x9f54030
---------------------------------------
Sizeof 'Pod': 16
Allocating 4 pods should take 64 bytes.
The size 'new' is actually asking for: 64 bytes.
Original address: 0x9f54048
Resulting address: 0x9f54048