2011-01-28 138 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" 
相關問題