GDB watches a class in an instance vector

Here is a very simplified version of my class:

Class MyClass { public: int sizeDesired; }; 

I create a MyClass vector of instances basically:

 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 is some kind of memory error (I think) that causes my program to crash. I noticed that the value of MyClass::sizeDesired is garbage when the program crashes. So, I want to set a watchdog for each MyClass:sizeDesired so that I can see exactly when the value of any of these elements changes.

Using GDB, how can I do this?


When I interrupt after clicking all instances of MyClass on std::vector<MyClass> basically, I then do

 (gdb) watch myvec[0].sizeDesired 

but gdb just freezes. It does not display the new command line (i.e., it does not show (gdb) on the next line ... just an empty line and nothing happens).


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

+4
source share
1 answer

I have not done much C ++ debugging in gdb, so this is probably all the known issues.

The problem with your watchpoint is apparently caused by the inability of gdb to actually execute some methods, such as the [] operator or method (). You can try this by simply printing myvec.at (0). This test seems to be missing from the watchpoint code, and it freezes gdb. (This is probably a known gdb bug, but I will check.)

Now a workaround. You can access the nth element of a vector using:

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

For sizeDesired, which will then be:

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

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

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

You will get a pointer to the field you want to see. Something like this will print: $ 1 = (int *) 0x40508c Now it prints:

 watch *((int*)0x40508c) continue 

Access to hardware (read / write) watchpoint 3: ((int) 0x40508c) ...

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

+2
source

Source: https://habr.com/ru/post/1486060/


All Articles