Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string cannot be printed in gdb when it's global variable, why?

I've got a teststring.cpp file, I wish to see if gdb can output std::string value:

#include<string>
#include<iostream>
using namespace std;
string sHello="hello world";
int main()
{
  cout<<sHello.c_str()<<endl;
  return 0;
}

Using g++ teststring.cpp -g, and gdb a.out

(gdb) b main
Breakpoint 1 at 0x400bfa: file teststring.cpp, line 7.
(gdb) r
Starting program: /home/x/a.out 

Breakpoint 1, main () at teststring.cpp:7
7     cout<<sHello.c_str()<<endl;
(gdb) p sHello
No symbol "sHello" in current context.

This is weird. If I move

string sHello="hello world";

to be the first line of main, like this:

#include<string>
#include<iostream>
using namespace std;
int main()
{
  string sHello="hello world";
  cout<<sHello.c_str()<<endl;
  return 0;
}

Then "p sHello" will work if I debug it. Well this is so strange to me.

Why it says no symbol?

More strange is, I used "$ readelf -s a.out|grep sHello" to check both versions of a.out, neither of them give me any result.

I suppose when there's symbol named "sHello":

sHello should appear in symbol table of ELF file, right?

like image 236
Hind Forsum Avatar asked Dec 05 '25 16:12

Hind Forsum


1 Answers

More strange is, I used "$ readelf -s a.out|grep sHello" to check both versions of a.out, neither of them give me any result.

You should try:

$ readelf -w a.out | fgrep sHello

<2fd3>   DW_AT_name        : (indirect string, offset: 0xce6): sHello

the -w switch displays the contents of the debug sections in the file, if any are present.

Why it says no symbol?

The culprit could be a mismatch between the compiler and debugger.

I cannot reproduce the problem (with g++ v5.4.0 and gdb 7.11.1):

(gdb) p sHello
$3 = {static npos = <optimized out>, 
      _M_dataplus = {<std::allocator<char>> =
      {<__gnu_cxx::new_allocator<char>> = {<No data fields>},
       <No data fields>}, 
      _M_p = 0x614c38 "hello world"}}

Maybe on a higher version of GDB you will get the expected behavior.

like image 133
manlio Avatar answered Dec 08 '25 04:12

manlio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!