goldenmean goldenmean - 1 year ago 96
C++ Question

Debugging C++ code involving use of: vector, string, STL

I am C++ beginner. When I try to debug C++ code using following constructs like string, vector of certain native types, STL etc, debugging gets tedious. I use MS Visual Studio 2010/ Visual C++ 2010 Express.


-- While using string as below:

string str;

getline(cin, str);

for(i=0; i<str.size();i++)

Watch window does not show values for str[i]. It says overloaded operator not found. I have to manually collapse the whole string variable str and see the char elem at that particular index, which gets cumbersome.

-- While using vector as below, same issue. If I set variable v1[k] in watch window same error.

vector<int> v1(100);

for(int k=0;k<100;k++)

-- Tried using simple STL iterators like it.begin() , it.end() and algorithms like sort(), reverse() , I could not debug inside those functions by stepping, or could not set break point into those.(I know they being inside STL or some such standard library they would be assured to be bug-free, but one can still use them incorrectly by passing something invalid/incorrect)

Coming from C language usage of many years, to C++, I find this lack of 'debug ability' , or some restrictions in that , painful, while I am trying to understand large chunks of C++ code written by someone else, at work.

My questions -

What are effective ways to debug working code to understand its functionality while using idioms like step in, breakpoints, watch point, watch windows. Is any particular debugger better/worse than other.(Like say gdb being better) or are there any specific tricks/tips to aid debugging.

In general how to analyze a C++ code to understand its working?

Answer Source

As you have found out, trying to use overloaded operators in the watch window simply won't work. You need to break open the objects and pull out the member variables.

In MSVC, std::vector has a member variable _Myfirst that points to the first element of its buffer. To get the item at index i you can add


To the watch window. You can also use


To show the first 10 elements of the array.

There should be a similar member variable for std::string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download