7

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?

Grammin
  • 11,808
  • 22
  • 80
  • 138

5 Answers5

10

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"
Community
  • 1
  • 1
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
6

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()
unwind
  • 391,730
  • 64
  • 469
  • 606
  • What would be the best want to actually look at the string then, do you have a gdb command that I can try? – Grammin Jan 28 '11 at 16:08
2

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

P.S. You should probably pass the string into function as a const reference.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • "You have a broken version of GCC, or GDB" - Haha. Apple's latest Xcode (4.5.2 in 2012). – jww Nov 23 '12 at 22:55
0

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"}}
Elalfer
  • 5,312
  • 20
  • 25
0

Had the same problem, solved including iostream library.

Dinsdale
  • 184
  • 3
  • 12