Question

Here is an extremely simplified version of my class:

Class MyClass {
public:
    int sizeDesired;
};

I'm creating a vector of MyClass instances in main:

int main(int argc, char **argv) {

    std::vector<MyClass> myvec;

    for(int i=0; i<10; ++i)
        myvec.push_back(MyClass());

    for(int i=0; i<myvec.size(); ++i)
        doWork(myvec[i]);

    return 0;
}

There's some memory corruption (I think) error that is causing my program to crash. I have observed that the value of MyClass::sizeDesired is garbage when the program crashes. So, I want to set a watchpoint on each MyClass:sizeDesired member so I can see exactly when any of these members' values changes.

Using GDB, how can I do this?


When I break after pushing all the instances of MyClass onto the std::vector<MyClass> in main, I then do

(gdb) watch myvec[0].sizeDesired

but GDB just hangs. It doesn't display a new command prompt (i.e., it doesn't show (gdb) on the succeeding line... just a blank line and nothing seems to be happening).


I'm open to non-GDB based solutions. If this type of inspection/monitoring is not possible in GDB, is there an alternative tool that could be used?

Was it helpful?

Solution

I did not do much C++ debugging in gdb, so these are probably all well known issues.

The problem with your watchpoint seems to be caused by gdb's inability to actually execute some methods, like [] operator or at() method. You can try this by just giving print myvec.at(0). It looks like this test is missing from watchpoint code, and it freezes the gdb. (It's probably known gdb bug, but I'll check.)

Now for the workaround. You can access n-th element of the vector using:

(MyClass*)(myvec._M_impl._M_start+n)

For sizeDesired that would then be:

(((MyClass*)(myvec._M_impl._M_start+n))->sizeDesired)

Adding a watchpoint to this expression still freezes gdb for some reason. But print works, so if you do something like:

print &(((MyClass*)(myvec._M_impl._M_start+3))->sizeDesired)

You will get pointer to the field you want to watch. Something like this will get printed out: $1 = (int *) 0x40508c Now issue:

watch *((int*)0x40508c)
continue

Hardware access (read/write) watchpoint 3: ((int)0x40508c) ...

BTW: Ideas how to print std containers were snitched from http://sourceware.org/ml/gdb/2008-02/msg00064/stl-views.gdb.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top