How to print total memory allocated for an object
Hi,
class Sample
{
int x, *ptr;
public:
Sample()
{
ptr = new int[100];
}
~Sample()
{
}
};
int main()
{
cout << "SizeofClass" << sizeof(Sample); //gives me output 8
Sample sm;
cout<< "SizeofObject" << sizeof(sm); //also gives me output 8
}
But i assume the size of sample object should be 4(x) + 400(ptr) = 404 bytes
Is there anyway that i can know or print the total memory alloacted which
x + ptr = 4 +400 = 404 bytes
Is my assumption correct ? Pls clarify me on this
Thanks
Kiran
Re: How to print total memory allocated for an object
It is not possible by any standard means. You'd have to either implement your solution based on size tracking of all dynamically allocated objects, or use some platform dependent ways (_msize for heap arrays, etc.)
Cheers
Re: How to print total memory allocated for an object
So, is it mean the size of an object is always caluculated at compile time irrespective of whether it contains a normal member variable or pointer variables ?
Any exception is there for this case ?
Re: How to print total memory allocated for an object
Quote:
Originally Posted by rsodimbakam
So, is it mean the size of an object is always caluculated at compile time irrespective of whether it contains a normal member variable or pointer variables ?
Yes. The sizeof() is a compile-time constant.
Quote:
Any exception is there for this case ?
No.
Regards,
Paul McKenzie
Re: How to print total memory allocated for an object
Quote:
But i assume the size of sample object should be 4(x) + 400(ptr) = 404 bytes
In that particular example the actual memory used would be
sizeof(int) + sizeof(int*) + sizeof(int)*100
which is,
x + ptr + (memory allocated to ptr)
Re: How to print total memory allocated for an object
+ any padding the compiler decides to add to the struct