当使用GDB调试Rust程序时,如何在格式化时打印内容?

3

当我尝试使用字符串格式化进行打印时,就像在C语言中调试时一样,我会遇到转换错误:

(gdb) printf "%s\n", "hello world"
Value can't be converted to integer.

期望结果:

(gdb) printf "%s\n", "hello world"
$2 = "hello world"

诊断信息:

$ rust-gdb -v
GNU gdb (GDB) 7.12.1
.....
1个回答

4
当使用printf时,它期望表达式是数字或指针。引自Commands for Controlled Output

printf模板,表达式...

表达式用逗号分隔,可以是数字或指针

如果我使用gdb的ptype命令检查"hello world"的类型,我会发现它是一个对象而不是数字或指针。
(gdb) ptype "hello world"
type = struct &str {
  data_ptr: u8 *,
  length: usize,
}

为了解决这个问题,请将参数更改为字符串的名为data_ptr的属性。
(gdb) ptype "hello world".data_ptr
type = u8 *

(gdb) p "hello world".data_ptr
$14 = (u8 *) 0x101100080 "hello world\000"

返回data_ptr应该可行,因为它是一个指针(u8 *),并且它指向字符串的起始地址。

(gdb) printf "%s\n", "hello world".data_ptr
hello world


注意不要将其与print混淆,因为这样将无法正常工作

(gdb) print "%s\n", "hello world".data_ptr
Could not convert character to `UTF-8' character set

1
不能保证 data_ptr 是以 NUL 结尾的,所以这似乎很可能在最糟糕的时候失败。 - Shepmaster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接