SetJmp/LongJmp:为什么会抛出段错误?
下面的代码总结了我目前遇到的问题。我当前的执行流程如下,我在 GCC 4.3 中运行。
jmp_buf a_buf;
jmp_buf b_buf;
void b_helper()
{
printf("entering b_helper");
if(setjmp(b_buf) == 0)
{
printf("longjmping to a_buf");
longjmp(a_buf, 1);
}
printf("returning from b_helper");
return; //segfaults right here
}
void b()
{
b_helper();
}
void a()
{
printf("setjmping a_buf");
if(setjmp(a_buf) == 0)
{
printf("calling b");
b();
}
printf("longjmping to b_buf");
longjmp(b_buf, 1);
}
int main()
{
a();
}
上述执行流程在 b_helper 返回后立即创建了一个段错误。几乎就好像只有 b_helper 堆栈帧有效,并且它下面的堆栈被擦除。
谁能解释为什么会发生这种情况?我猜这是一个 GCC 优化,正在删除未使用的堆栈帧或其他东西。
谢谢。
The following code summarizes the problem I have at the moment. My current execution flow is as follows and a I'm running in GCC 4.3.
jmp_buf a_buf;
jmp_buf b_buf;
void b_helper()
{
printf("entering b_helper");
if(setjmp(b_buf) == 0)
{
printf("longjmping to a_buf");
longjmp(a_buf, 1);
}
printf("returning from b_helper");
return; //segfaults right here
}
void b()
{
b_helper();
}
void a()
{
printf("setjmping a_buf");
if(setjmp(a_buf) == 0)
{
printf("calling b");
b();
}
printf("longjmping to b_buf");
longjmp(b_buf, 1);
}
int main()
{
a();
}
The above execution flow creates a segfault right after the return in b_helper. It's almost as if only the b_helper stack frame is valid, and the stacks below it are erased.
Can anyone explain why this is happening? I'm guessing it's a GCC optimization that's erasing unused stack frames or something.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只能
longjmp()
备份调用堆栈。对longjmp(b_buf, 1)
的调用是开始出错的地方,因为b_buf
引用的堆栈帧在longjmp(a_buf) 之后不再存在
。来自
longjmp
的文档:这包括通过函数的
longjmp()
“返回”。You can only
longjmp()
back up the call stack. The call tolongjmp(b_buf, 1)
is where things start to go wrong, because the stack frame referenced byb_buf
no longer exists after thelongjmp(a_buf)
.From the documentation for
longjmp
:This includes "returning" through a
longjmp()
out of the function.标准对于
longjmp()
是这么说的(7.13.2.1 longjmp 函数):脚注对此进行了澄清:
所以你不能
longjmp()
back &跨嵌套的setjmp
/longjmp
集。The standard says this about
longjmp()
(7.13.2.1 The longjmp function):with a footnote that clarifies this a bit:
So you can't
longjmp()
back & forth across nestedsetjmp
/longjmp
sets.