Josh Renwald
Josh Renwald

Reputation: 1479

Dumping the memory contents of a object

In a game that I mod for they recently made some changes which broke a specific entity. After speaking with someone who figured out a fix for it, they only information they gave me was that they "patched it" and wouldn't share anymore.

I am basically trying to remember how to dump the memory contents of a class object at runtime. I vaguely remember doing something similar before, but it has been a very long time. Any help on remember how to go about this would be most appreciated.

Upvotes: 7

Views: 4909

Answers (2)

Didier Trosset
Didier Trosset

Reputation: 37467

template <class T>
void dumpobject(T const *t) {
    unsigned char const *p = reinterpret_cast<unsigned char const *>(t);
    for (size_t n = 0 ; n < sizeof(T) ; ++n)
        printf("%02d ", p[n]);
    printf("\n");
}

Upvotes: 9

ereOn
ereOn

Reputation: 55776

Well, you may reinterpret_cast your object instance as a char array and display that.

Foo foo; // Your object
 // Here comes the ugly cast
const unsigned char* a = reinterpret_cast<const unsigned char*>(&foo);

for (size_t i = 0; i < sizeof(foo); ++i)
{
  using namespace std;
  cout << hex << setw(2) << static_cast<unsigned int>(a[i]) << " ";
}

This is ugly but should work.

Anyway, dealing with the internals of some implementation is usually not a good idea.

Upvotes: 2

Related Questions