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?
The usual way to examine data in your program is with the print command (abbreviated p ), or its synonym inspect . It evaluates and prints the value of an expression of the language your program is written in (see section Using GDB with Different Languages).
We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.
C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With