Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dumping the memory contents of a object

Tags:

c++

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.

like image 501
Josh Renwald Avatar asked Oct 27 '10 09:10

Josh Renwald


2 Answers

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");
}
like image 116
Didier Trosset Avatar answered Nov 09 '22 14:11

Didier Trosset


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.

like image 29
ereOn Avatar answered Nov 09 '22 13:11

ereOn