使用 gdb 检查标准容器(std: : map)内容

假设有这样的东西:

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

我希望能够检查从 gdb 运行程序的映射的内容。
如果我尝试使用下标运算符,我会得到:

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

使用 find 方法不会产生更好的结果:

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

有办法完成吗?

109558 次浏览

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

Try De-Referencing STL Containers: on this page: http://www.yolinux.com/TUTORIALS/GDB-Commands.html

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)

The stl-views.gdb used to be the best answer there was, but not anymore.

This isn't integrated into the mainline GDB yet, but here is what you get using the 'archer-tromey-python' branch:

(gdb) list
1   #include <map>
2   int main(){
3       std::map<int,int> m;
4       m[1] = 2;
5       m[2] = 4;
6       return 0;
7   }
(gdb) break 6
Breakpoint 1 at 0x8048274: file map.cc, line 6.
(gdb) run


Breakpoint 1, main () at map.cc:6
6       return 0;
(gdb) print m
$1 = std::map with 2 elements = {
[1] = 2,
[2] = 4
}
(gdb) quit

You can get around the second problem (Cannot evaluate function -- may be inlined) by making sure that your compiler uses DWARF-2 (or 3 or 4) debugging information when you compile your program. DWARF-2 includes inlining information, so you should be able to use either of the methods you described to access elements of your std::map container.

To compile with DWARF-2 debug info, add the -gdwarf-2 flag to your compile command.

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.

The answers above are working and fine. In case you are using stl-views.gdb, here is the proper way of viewing the maps and elements inside it. Let your map is as follows : std::map<char, int> myMap;

(gdb) pmap myMap char int

i.e. pmap <variable_name> <left_element_type> <right_element_type> to see the elements in the map.

Hope that helps.