疑似一个 gdb 的 bug
  • 板块学术版
  • 楼主uwagjaynoi
  • 当前回复6
  • 已保存回复6
  • 发布时间2022/7/11 06:46
  • 上次更新2023/10/27 21:09:46
查看原帖
疑似一个 gdb 的 bug
77144
uwagjaynoi楼主2022/7/11 06:46

以下描述了此问题的复现流程。想知道有没有人遇见过类似的问题,可能是什么原因造成的,以及应该如何规避?谢谢!

#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)

file ./a
break 15
run
print &Inst 输出:(Struct *) 0x555555558180 <Inst>
call Inst.func()

然后会出现

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;

继续调试

print this 输出 (Struct * const) 0x7fffffffde70
print p 输出 (Pair *) 0x0

注意到这边 this=0x7fffffffde70 与刚刚 print 的地址不符。这应该是一个错误的指针,使得该位置“对应结构体”的 p=null,无法解引用。然而 14 行正常说明程序内调用 Inst.func() 得到了正确结果。

将 Pair 改为手写可以使问题不出现。

加入 -std=c++98 编译选项可以使问题不出现。

2022/7/11 06:46
加载中...