Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inspecting standard container (std::map) contents with gdb

Tags:

c++

map

stl

gdb

Supposing to have something like this:

#include <map>
int main(){
    std::map<int,int> m;
    m[1] = 2;
    m[2] = 4;
    return 0;
}

I would like to be able to inspect the contents of the map running the program from gdb.
If I try using the subscript operator I get:

(gdb) p m[1]
Attempt to take address of value not located in memory.

Using the find method does not yield better results:

(gdb) p m.find(1)
Cannot evaluate function -- may be inlined

Is there a way to accomplish this?

like image 913
Paolo Tedesco Avatar asked Jan 09 '09 10:01

Paolo Tedesco


3 Answers

The existing answers to this question are very out of date. With a recent GCC and GDB it Just WorksTM thanks to the built-in Python support in GDB 7.x and the libstdc++ pretty printers that come with GCC.

For the OP's example I get:

(gdb) print m
$1 = std::map with 2 elements = {[1] = 2, [2] = 4}

If it doesn't work automatically for you see the first bullet point on the STL Support page of the GDB wiki.

You can write Python pretty printers for your own types too, see Pretty Printing in the GDB manual.

like image 185
Jonathan Wakely Avatar answered Nov 18 '22 19:11

Jonathan Wakely


I think there isn't, at least not if your source is optimized etc. However, there are some macros for gdb that can inspect STL containers for you:

http://sourceware.org/ml/gdb/2008-02/msg00064.html

However, I don't use this, so YMMV

like image 36
jpalecek Avatar answered Nov 18 '22 20:11

jpalecek


There's always the obvious: Define your own test-function... Call it from gdb. E.g.:

#define SHOW(X) cout << # X " = " << (X) << endl

void testPrint( map<int,int> & m, int i )
{
  SHOW( m[i] );
  SHOW( m.find(i)->first );
}

int
main()
{
    std::map<int,int> m;
    m[1] = 2;
    m[2] = 4;
    return 0;  // Line 15.
}

And:

....
Breakpoint 1 at 0x400e08: file foo.C, line 15.
(gdb) run
Starting program: /tmp/z/qD 

Breakpoint 1, main () at qD.C:15
(gdb) call testPrint( m, 2)
m[i] = 4
(*m.find(i)).first = 2
(gdb) 
like image 25
Mr.Ree Avatar answered Nov 18 '22 19:11

Mr.Ree