简体   繁体   中英

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

Say I have the code:

std::string str = "random";

function(str);

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

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

GDB is probably missing debug information for the STL for whatever reason. Using Employed Russian's 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 "$▒▒"}}

Which is an interpretation of the 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"

gdb is probably just showing you the byte-string-interpretation of the string class' internals. Try this to verify/work around:

$ print str.c_str()

You have a broken version of GCC, or GDB, or you are trying to print the string at the wrong place. Here is 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 pretty 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 into function as a const reference.

Did you compile your binary with debug information? Like g++ -g test.cpp

Mine is showing correct information:

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

有同样的问题,解决了包括iostream库。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM