std::string 是全局变量时不能在 gdb 中打印,为什么?
std::string cannot be printed in gdb when it's global variable, why?
我有一个teststring.cpp文件,我想看看gdb是否可以输出std::string值:
#include<string>
#include<iostream>
using namespace std;
string sHello="hello world";
int main()
{
cout<<sHello.c_str()<<endl;
return 0;
}
使用g++ teststring.cpp -g和gdb .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.
这很奇怪。如果我移动
string sHello="hello world";
作为main的第一行,如下:
#include<string>
#include<iostream>
using namespace std;
int main()
{
string sHello="hello world";
cout<<sHello.c_str()<<endl;
return 0;
}
然后"p hello "将工作,如果我调试它。这对我来说太奇怪了。
为什么没有符号?
更奇怪的是,我使用"$ readelf -s a.out|grep hello"来检查a.out的两个版本,它们都没有给我任何结果。
我想当有一个名为" hello "的符号时:
shell应该出现在ELF文件的符号表中,对吗?
更奇怪的是,我使用"$ readelf -s a.out|grep hello"来检查a.out的两个版本,它们都没有给我任何结果。
你应该试试:
$ readelf -w a.out | fgrep sHello
<2fd3> DW_AT_name : (indirect string, offset: 0xce6): sHello
-w
开关显示文件中调试部分的内容,如果有的话。
为什么没有符号?
原因可能是编译器和调试器不匹配。
我无法重现这个问题(使用g++ v5.4.0和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"}}
也许在更高版本的GDB上你会得到预期的行为
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 为什么我的字符串变量没有打印完整的字符串?
- 为什么我在尝试在单向链表中打印元素时会出现这个永无止境的循环
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 为什么平均打印数组元素比打印单个对象慢C++?
- 了解运算符重载和迭代器,为什么它会打印出"wrhrwwr"?
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 为什么我的打印功能不起作用?链表
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 为什么数组不打印第一个元素?
- 为什么在C++中增加指针后打印了一个值而不是 NULL/0?
- 为什么Qt Creator的应用程序输出不能从spdlog记录器打印
- 为什么打印 c 样式字符串的'address of index n'会导致子字符串的输出
- 为什么字符串没有更新并且最终没有打印任何内容