社区讨论

疑似一个 gdb 的 bug

学术版参与者 3已保存回复 6

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
6 条
当前快照
1 份
快照标识符
@lo8mri4y
此快照首次捕获于
2023/10/27 21:09
2 年前
此快照最后确认于
2023/10/27 21:09
2 年前
查看原帖
以下描述了此问题的复现流程。想知道有没有人遇见过类似的问题,可能是什么原因造成的,以及应该如何规避?谢谢!
CPP
#include <utility>
typedef std::pair<int,int> Pair;
struct Struct
{
	Pair *p;
	Pair func(void)
	{
		return *p;
	}
}Inst;
int main(void)
{
	Inst.p=new Pair[1]{{-1,0}};
	int val(Inst.func().first);
	++val;//call Inst.func()
	return 0;
}
g++ Ubuntu 9.4.0-1ubuntu1~20.04.1
gdb Ubuntu 9.2-0ubuntu1~20.04.1
编译选项 -g -fsanitize=undefined
若直接运行程序则不会报错,正常结束。
以下为 gdb 调试流程(源文件名 a.cpp,可执行文件名 a)
CPP
file ./a
break 15
run
print &Inst 输出:(Struct *) 0x555555558180 <Inst>
call Inst.func()
然后会出现
CPP
a.cpp:8:11: runtime error: reference binding to null pointer of type 'const struct pair'
a.cpp:8:11: runtime error: load of null pointer of type 'const struct pair'
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555369 in Struct::func (this=0x7fffffffde70) at a.cpp:8
8			return *p;
继续调试
CPP
print this 输出 (Struct * const) 0x7fffffffde70
print p 输出 (Pair *) 0x0
注意到这边 this=0x7fffffffde70 与刚刚 print 的地址不符。这应该是一个错误的指针,使得该位置“对应结构体”的 p=null,无法解引用。然而 14 行正常说明程序内调用 Inst.func() 得到了正确结果。
将 Pair 改为手写可以使问题不出现。
加入 -std=c++98 编译选项可以使问题不出现。

回复

6 条回复,欢迎继续交流。

正在加载回复...