Listing 2
template <class Super> struct UseSizeHeap : public Super { static size_t getSize(const void * ptr) { return ((freeObject *) ptr - 1)->sz; } protected: union freeObject { size_t sz; double _dummy; // for alignment. }; }; template <class SuperHeap> class SizeHeap : public UseSizeHeap<SuperHeap> { typedef typename UseSizeHeap<SuperHeap>::freeObject freeObject; public: void * malloc(const size_t sz) { // Add room for a size field. freeObject * ptr = (freeObject *) SuperHeap::malloc(sz + sizeof(freeObject)); // Store the requested size. ptr->sz = sz; return (void *) (ptr + 1); } void free(void * ptr) { SuperHeap::free((freeObject *)ptr - 1); } };