You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GDB调试时读取std::string变量报错问题咨询

GDB调试std::string变量报错问题解析

复现代码

#include <string>

struct S
{ 
  S(const std::string& es)
    : first_string(func().c_str())
  {}

  std::string func()
  {
    std::string my_string = "some string"; // Breakpoint here
    return my_string;
  }

  std::string first_string;
  std::string second_string;
};

int main()
{
  std::string foo;
  S s("mystring");
}

问题现象

在my_string的初始化行打断点,执行print my_string或者info locals命令时,GDB抛出错误:

my_string = <error reading variable: Cannot create a lazy string with address 0x0, and a non-zero length.>
测试用的GDB版本是8.2-20,只要移除代码里任意一个其他变量(比如second_string或者foo),这个错误就会消失。

结论:这是GDB的bug,不是预期现象

原因说明

这属于GDB在处理栈帧布局和C++临时对象时的已知缺陷。当代码里存在多个std::string变量时,GDB解析调试信息时出现偏移计算错误,错误地把my_string内部指向字符串数据的指针当成了0x0,但实际上该变量已经完成初始化,数据地址并非空指针。

移除其他变量后,栈的内存布局发生变化,刚好避开了GDB的计算错误,所以问题就不复存在了。

解决方法

  1. 升级GDB版本:9.x及以上的GDB已经修复了不少这类std::string调试相关的bug,升级后大概率能解决问题。
  2. 临时调试技巧:如果暂时没法升级,可以在func()里加一行无关代码(比如volatile auto dummy = my_string;),强制编译器保留变量的完整调试信息;或者直接打印my_string.c_str()来查看字符串内容。

内容的提问来源于stack exchange,提问作者user1166

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 00:44:52