在GDB中创建C++字符串

Joh*_*gko 24 c++ gdb

std::string在GDB中创建(或任何C++对象)时遇到了麻烦.我尝试了以下很多变化,但似乎没有任何变化:

(gdb) p std::string("hello")
A syntax error in expression, near `"hello")'.
Run Code Online (Sandbox Code Playgroud)

有办法吗?

(我很惊讶我在网上找不到任何相关内容.我开始认为我的GDB是错误的还是我做错了什么.)

小智 30

您应该能够在GDB中构造一个新的std :: string.您希望在堆上分配空间来保存std :: string对象,调用默认构造函数并分配字符串值.这是一个例子:

(gdb) call malloc(sizeof(std::string))
$1 = (void *) 0x91a6a0
(gdb) call ((std::string*)0x91a6a0)->basic_string()
(gdb) call ((std::string*)0x91a6a0)->assign("Hello, World")
$2 = (std::basic_string<char, std::char_traits<char>, std::allocator<char> > &) @0x91a6a0: {static npos = <optimized out>, _M_dataplus = {<std::allocator<char>> = {<__gnu_cxx::new_allocator<char>> = {<No data fields>}, <No data fields>}, _M_p = 0x91a6f8 "Hello, World"}}
(gdb) call SomeFunctionThatTakesAConstStringRef(*(const std::string*)0x91a6a0)
Run Code Online (Sandbox Code Playgroud)

  • 使用"便利变量"可以做得更简单.类似于:(gdb)set $ mystr =(std :: string*)malloc(sizeof(std :: string)),(gdb)调用$ mystr-> basic_string(),(gdb)调用$ mystr-> assign( "foo"),(gdb)调用some_function(*$ mystr) (7认同)
  • `(gdb) call malloc(sizeof(std::string))` 结果是`命名空间“std”中没有符号“string”。`我做错了什么? (2认同)