Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to distinguish what type of memory used by the object instance?

Tags:

c++

If i have this code :

#include <assert.h>

class Foo {
public:
    bool is_static();
    bool is_stack();
    bool is_dynamic();
};

Foo a;

int main()
{
    Foo b;
    Foo* c = new Foo;

    assert( a.is_static()  && !a.is_stack()  && !a.is_dynamic());
    assert(!b.is_static()  &&  b.is_stack()  && !b.is_dynamic());
    assert(!c->is_static() && !c->is_stack() &&  c->is_dynamic());

    delete c;
}

Is it possible to implement is_stack, is_static, is_dynamic method to do so in order to be assertions fulfilled?

Example of use: counting size of memory which particular objects of type Foo uses on stack, but not counting static or dynamic memory

like image 802
user3123061 Avatar asked Dec 06 '25 02:12

user3123061


2 Answers

This cannot be done using standard C++ facilities, which take pains to ensure that objects work the same way no matter how they are allocated.

You can do it, however, by asking the OS about your process memory map, and figuring out what address range a given object falls into. (Be sure to use uintptr_t for arithmetic while doing this.)

like image 156
Potatoswatter Avatar answered Dec 08 '25 16:12

Potatoswatter


Scroll down to the second answer that gives a wide array of available options depending on the Operating System:

How to determine CPU and memory consumption from inside a process?

I would also recommend reading this article on Tracking Memory Alloactions in C++:

http://www.almostinfinite.com/memtrack.html

Just be aware that it's a ton of work.

like image 31
B.K. Avatar answered Dec 08 '25 16:12

B.K.