fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Base
  5. {
  6. public:
  7. Base() {};
  8. virtual ~Base() {};
  9.  
  10. void* operator new[](size_t size)
  11. {
  12. size_t* ptr = static_cast<size_t*>(malloc((size + 1) * sizeof(size_t)));
  13. if (ptr == nullptr)
  14. {
  15. throw std::bad_alloc();
  16. }
  17. *ptr = size;
  18. return (ptr + sizeof(size_t));
  19. }
  20.  
  21. void operator delete[](void* ptr, size_t size)
  22. {
  23. if (ptr != nullptr)
  24. {
  25. free(static_cast<size_t*>(ptr) - sizeof(size_t));
  26. }
  27. }
  28. };
  29.  
  30. class Derived : public Base
  31. {
  32. public:
  33. Derived(int value) :
  34. m_value(value)
  35. {
  36. }
  37.  
  38. private:
  39. int m_value;
  40. };
  41.  
  42. int main() {
  43. Derived* i = new Derived[18] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 42, 100 };
  44. void* i2 = i;
  45. size_t* size = (static_cast<size_t*>(i2) - sizeof(size_t));
  46. printf("Size: '%d'\n", (int)*size);
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Size: '0'