2011-01-28 139 views
7

说我有代码:为什么gdb中的print命令为C++ std :: strings返回 035?

std::string str = "random"; 

function(str); 

void function (std::string str) 
{ 
    std::cout << str << std::endl; 
} 

如果我一步通过这个代码在gdb,然后进入功能,并做p str它会打印出这样的事情\362\241但COUT将输出到屏幕上正确字符串random。如果有的话,有没有人看过这个,我该怎么办?我是否在gdb中使用了print命令,或者它与编译器如何解释字符串有关?

+0

不\ 035解释为索引到ASCII表八进制三重? – evandrix 2011-01-28 16:02:00

+0

我也在思考这些问题,但我无法弄清楚为什么,如何或如果这与问题有什么关系 – Grammin 2011-01-28 16:04:17

+0

如何超集:http://stackoverflow.com/questions/11606048/pretty-printing -stl-containers-in-gdb – 2017-04-12 08:00:16

回答

2

你有一个破碎的GCC版本,或GDB,或者你想在错误的地方打印字符串。下面是它应该是什么样子(使用g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3GNU gdb (GDB) 7.2.50.20110127-cvs与STL漂亮打印机启用):

#include <string> 
#include <iostream> 

void function (std::string str) 
{ 
    std::cout << str << std::endl; 
} 

int main() 
{ 
    std::string str = "random"; 
    function(str); 
} 

$ g++ -g t.cc && gdb -q ./a.out 
Reading symbols from /usr/local/tmp/a.out...done. 
(gdb) b function 
Breakpoint 1 at 0x400b30: file t.cc, line 6. 
(gdb) run 

Breakpoint 1, function (str="random") at t.cc:6 
6  std::cout << str << std::endl; 
(gdb) p str 
$1 = "random" 
(gdb) q 

附:您应该可以将该字符串作为const引用传递给函数。

4

gdb可能只是向您显示字符串类的内部字节字符串解释。尝试此验证/变通办法:

$ print str.c_str() 
0

你是否用二次调试信息编译你的二进制文件?像g++ -g test.cpp

矿正显示出正确的信息:

(gdb) p s 
$2 = {static npos = <optimized out>, 
    _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x804b014 "Hello world"}} 
9

GDB可能因任何原因缺少STL的调试信息。使用Employed Russian's example与G ++(GCC)4.3.4 20090804(释放)1和GNU GDB 6.8.0.20080328-CVS(Cygwin的特),我得到下面的输出:

(gdb) p str 
$1 = {static npos = <optimized out>, 
    _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {< 
No data fields>}, <No data fields>}, _M_p = 0x28cce8 "$▒▒"}} 

哪一个是原始数据的解释字段std::string。要获得实际的字符串数据,我不得不重新解释_M_p场为指针:

(gdb) p *(char**)str._M_dataplus._M_p 
$2 = 0xd4a224 "random" 
相关问题