Re: memory size allocated by new
On Mar 6, 7:59 pm, "mast...@yahoo.com" <mast...@yahoo.com> wrote:
This question has been posted to this forum before and I read the
thread but found that the answers were perhaps imcomplete, so I am
trying again.
Whenever I am creating objects I would like to keep track of the
memory which is used for each object (for stats purpose). They are 2
basic approaches, one is to write a Memory manager type of class where
new & delete would be overloading the standard new & delete operator.
Each time the new member function of this class would be called I
could update a variable to would keep track of the bytes allocated by
new. This not completly satisafactory for me as this would be global
to the application.
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?
Another way is to just recompute the size of the byte arrays and add
the result to a member variable. Something like that...
class A
{
private:
int *data;
float *floatData;
size_t mem;
public:
A( size_t arraySize, size_t arraySize2 )
{
mem = 0;
data = new int[ arraySize ];
dataFloat = new float[ arraySize2 ]
mem += sizeof( int ) * arraySize;
mem += sizeof( float ) * arraySize2;
}
}
I'm not getting this either. You are allocating arrays, and trying to
store the size of the arrays, but you only want it done in a class?
I have read that 'new' reserves the memory which is needed for the
array of a certain type, plus some additional info at the beginning at
this array (which delete uses to know what is the size of the array it
needs to free). So instead of recompute the size of the array in bytes
and summing up the result to the variable mem is there a way one could
access the size of an array in bytes used by an array or created by
new ?
Ok, this I get. An array will be sizeof(type)*numberOfElements but if
the type has a destructor, then you will have to add sizeof(size_t) to
it.
If you just want to know how many bytes are being allocated globally,
do this:
<sourceFile>
static size_t bytesAllocatedSoFar = 0;
void* ::operator new(size_t size)
{
bytesAllocatedSoFar += size;
return malloc(size);
}
void* ::operator new[](size_t size)
{
bytesAllocatedSoFar += size;
return malloc(size);
}
void ::operator delete(void *memory)
{
return free(memory);
}
void ::operator delete[](void *memory)
{
return free(memory);
}
</sourceFile>
But if any part of your programme uses malloc, this information is
lost.
If you want to access bytesAllocatedSoFar you will either define it
extern in the header file (and remove static from the source file), or
create an access function prototype in the header file and define it
in the source as returning bytesAllocatedSoFar.
Hope this helps.
Adrian