Why does the print command in gdb return \ 035 for C ++ std :: strings?

Say I have a code:

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

If I go through this code in gdb and then go into a function and do p str , it will output something like this \362\241 , but cout will return the correct random string to the screen. Has anyone seen this before, if so, what should I do? Am I using the print command incorrectly in gdb or does it have something to do with how the compiler interprets the line?

+7
source share
4 answers

You have a broken version of GCC or GDB, or you are trying to print a string in the wrong place. Here's what it should look like (using g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3 and GNU gdb (GDB) 7.2.50.20110127-cvs with STL printers enabled):

 #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 

PS You should probably pass the string as a const reference.

+2
source

For some reason, GDB probably does not have debugging information for the STL. Using the above Russian example with g ++ (GCC) 4.3.4 20090804 (release) 1 and GNU gdb 6.8.0.20080328-cvs (cygwin-special), I get the following output

 (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 "$▒▒"}} 

What is the interpretation of raw data fields in std::string . To get the actual string data, I have to reinterpret the _M_p field as a pointer:

 (gdb) p *(char**)str._M_dataplus._M_p $2 = 0xd4a224 "random" 
+9
source

gdb probably just shows you a byte interpretation of the internal elements of a string class. Try this to verify / work:

 $ print str.c_str() 
+5
source

Have you compiled your binary file with debugging information? Like g++ -g test.cpp

Mine shows the correct information:

 (gdb) ps $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"}} 
0
source

All Articles