views:

5172

answers:

4

I want to examine the contents of a std::vector in GDB, how do I do it? Let's say it's a std::vector<int> for the sake of simplicity.

+34  A: 

With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:

print *(myVector._M_impl._M_start)@myVector.size()

To print only the first N elements, do:

print *(myVector._M_impl._M_start)@N

Explanation

This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:

myVector._M_impl._M_start

And the GDB command to print N elements of an array starting at pointer P is:

print P@N
therefromhere
If it wasn't so darn useful I'd say this was a scam to improve your reputation! ;)
David Holm
Hehe, it's something that's bugged me before, so I just looked it up this morning and added it as a memo to myself (as Jeff himself recommended).
therefromhere
+4  A: 

'Watching' STL containers while debugging is somewhat of a problem. Here are 3 different solutions I have used in the past, none of them is perfect.

1) Use GDB scripts from http://www.stanford.edu/~afn/gdb_stl_utils/ These scripts allow you to print the contents of almost all STL containers. The problem is that this does not work for nested containers like a stack of sets.

2) Visual Studio 2005 has fantastic support for watching STL containers. This works for nested containers but this is for their implementation for STL only and does not work if you are putting a STL container in a Boost container.

3) Write your own 'print' function (or method) for the specific item you want to print while debugging and use 'call' while in GDB to print the item. This is a little tricky because if your print function is not being called anywhere in the code g++ will do dead code elimination and the 'print' function will not be found by GDB (you will get a message saying that the function is inlined). Make a pseudo call so that the code is not eliminated.

Nikhil
+1  A: 

A comment on the above post - since I can't comment without 50 points. You can see your custom print method in gdb if you change the compiler to not optimize the code (i.e. set the -O flag to zero) and this should keep your function visible during debugging.

+3  A: 

To view vector std::vector myVector contents, just type in GDB:

(gdb) print myVector

This will produce an output similar to:

$1 = std::vector of length 3, capacity 4 = {10, 20, 30}

To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on gdb wiki.

What is more, after installing above, this works well with Eclipse C++ debugger GUI (and any other IDE using GDB, as I think).

Michał Oniszczuk