#include #include //for malloc and free #include "obj.h" using namespace std; void *operator new[](size_t n); void operator delete[](void *p); int main() { cout << "How many elements do you want to allocate? "; size_t n; cin >> n; int *const p1 = new int [n]; //calls operator new[] in line 48 for (size_t i = 0; i < n; ++i) { cout << "The int at address " << p1 + i << " holds " << p1[i] << ".\n"; } cout << "The hidden numbers are " //unofficial << reinterpret_cast(p1)[-2] << " and " << reinterpret_cast(p1)[-1] << ".\n"; delete[] p1; //calls operator delete[] in line 62 cout << "\nAn obj is " << sizeof (obj) << " bytes, an array of " << n << " of them is " << n * sizeof (obj) << " bytes, and a size_t is " << sizeof (size_t) << " bytes.\n"; obj *const p2 = new obj [n]; //calls operator new[] in line 48 for (size_t i = 0; i < n; ++i) { cout << "The obj at address " << p2 + i << " holds " << p2[i] << ".\n"; } cout << "The hidden numbers are " << reinterpret_cast(p2)[-3] << ", " << reinterpret_cast(p2)[-2] << ", and " << reinterpret_cast(p2)[-1] << ".\n"; delete[] p2; //calls operator delete[] in line 62 return EXIT_SUCCESS; } void *operator new[](size_t n) { if (void *const p = malloc(n)) { cout << "operator new[](" << n << ") returns " << p << " with hidden numbers " << reinterpret_cast(p)[-2] << " and " << reinterpret_cast(p)[-1] << ".\n"; return p; } cerr << "operator new[](" << n << ") out of store.\n"; exit(EXIT_FAILURE); } void operator delete[](void *p) { cout << "operator delete[](" << p << ") with hidden numbers " << reinterpret_cast(p)[-2] << " and " << reinterpret_cast(p)[-1] << ".\n"; free(p); }