CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Sep 2008
    Posts
    48

    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

  2. #2
    Join Date
    Dec 2004
    Location
    Poland
    Posts
    1,165

    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
    B+!
    'There is no cat' - A. Einstein

    Use &#91;code] [/code] tags!

    Did YOU share your photo with us at CG Members photo gallery ?

  3. #3
    Join Date
    Sep 2008
    Posts
    48

    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 ?

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    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.
    Any exception is there for this case ?
    No.

    Regards,

    Paul McKenzie

  5. #5
    Join Date
    Aug 2007
    Posts
    858

    Re: How to print total memory allocated for an object

    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)

  6. #6
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: How to print total memory allocated for an object

    + any padding the compiler decides to add to the struct

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured