Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the memory of a c++ object at runtime

I'm trying to determine the size of an object at runtime. sizeof doesn't work because this returns the size at compile time. Here is an example of what I mean:

class Foo 
{
public:
    Foo() 
    {
        c = new char[1024*1024*1024];
    }
    ~Foo() 
    { 
        delete[] c; 
    }

private:
    char *c;
};

In this case, sizeof(Foo) will be 4 bytes and not ~1GB. How can I determine the size of Foo at runtime? Thanks in advance.

like image 602
Dr. Jay Avatar asked Feb 02 '23 23:02

Dr. Jay


2 Answers

The size of Foo is constant. The ~1GB of chars does not technically belong to the object, just the pointer to it does. The chars are only said to be owned by the object, because the object is responsible for allocating and deallocating memory for them. C++ does not provide features that allow you to find out how much memory an object has allocated. You have to keep track of that yourself.

like image 94
Oswald Avatar answered Feb 05 '23 17:02

Oswald


You need to keep track of it yourself somehow. For example:

struct Foo 
{
    Foo()
        : elements(1024 * 1024 * 1024) 
    {
        c.reset(new char[elements]);
    }

    boost::scoped_array<char> c;
    int elements;
};

Note that you should use a smart pointer container for managing dynamically allocated objects so that you don't have to manage their lifetimes manually. Here, I've demonstrated use of scoped_array, which is a very helpful container. You can also use shared_array or use shared_ptr with a custom deleter.

like image 22
James McNellis Avatar answered Feb 05 '23 16:02

James McNellis