Re: memory size allocated by new
On Mar 6, 9:25 pm, "mast...@yahoo.com" <mast...@yahoo.com> wrote:
Sorry, I'm not understanding you. Are you asking for some way of
tracking how many bytes are being allocated globally? Or only in
certain spots?
Sorry Adrian I wasn't clear. I am only interested in the memory used
by objects of class A. So for example if they are 100 objects of class
A which are created all with different sizes for floatData & data, I
want to know how memory is used by these 100 objects. This is why I
wanted to avoid using some sort of memory manager class that would
have new and delete overloaded.
My question was also about these extra bits that the new operator
seems to control to save info about the size of the byte arrays it has
created. I was wondering if that info could be accessed somehow, so
one could get that value from there !
First off, the new operator does not 'control' the number of bytes it
allocates, unless by control, you mean add to beyond what the compiler
is going to add to it. I.e. I stated that there could be a size_t
value at the begining of an array, this is done by the compiler, not
the new operator. The new operator is passed the size the compiler
needs to do its thing, and as stated by Ron, it is implementation
dependent. However, the new operator can add extra stuff if it wants,
as long as the returned pointer points to the space that the compiler
can use.
The following is untested, (I just wrote it) but it should work. It
basicly wraps the new operator in a class template. Destructors
should be called approprately.
<headerFile>
/************************************************************
* Written by Adrian Hawryluk (C) Mar 6, 2007
* ----------------------------------------------------------
* You may use and add to this free of charge, but
* please keep this header intact, and if you modify
* please share your mods with everyone else.
*
* Usage:
*
* int * integer = alloc<int>::newObj();
* cout << allocBase::totalBytesAllocated() << endl; // 4
* int * intArray = alloc<int>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 80
*
* class foo {
* int bar;
* public: ~foo() {}
* };
*
* foo * fooArray = alloc<foo>::newObjArray(20);
* cout << allocBase::totalBytesAllocated() << endl; // 84?
*
************************************************************/
class allocBase
{
static size_t bytesAllocatedSoFar;
public:
static size_t totalBytesAllocated() { return bytesAllocatedSoFar; }
};
template<class T>
class alloc{
T obj;
void * operator new(size_t size) { bytesAllocatedSoFar += size;
return ::operator new(size); }
void * operator new[](size_t size) { bytesAllocatedSoFar += size;
return ::operator new(size); }
public:
static T* newObj() { return reinterpret_cast<T*>(new T()); }
static T* newObjArray(int numberOfElements) { return
reinterpret_cast<T*>(new T[numberOfElements]); }
};
</headerFile>
<sourceFile>
size_t allocBase::bytesAllocatedSoFar = 0;
</sourceFile>
Enjoy,
Adrian