SetJmp / LongJmp:为什么这会抛出segfault? [英] SetJmp/LongJmp: Why is this throwing a segfault?
问题描述
以下代码总结了我目前遇到的问题。我目前的执行流程如下,我在GCC 4.3中运行。
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();
}
上述执行流程在b_helper中返回后立即创建一个segfault。它几乎就像只有b_helper堆栈框架是有效的,它下面的堆栈被擦除。
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.
任何人都可以解释为什么会发生这种情况?我猜这是一个GCC优化,它正在擦除未使用的堆栈帧或某事。
Can anyone explain why this is happening? I'm guessing it's a GCC optimization that's erasing unused stack frames or something.
谢谢。
推荐答案
只有 longjmp()
回到调用堆栈。调用 longjmp(b_buf,1)
是事情开始出错的地方,因为 b_buf
longjmp
You can only longjmp()
back up the call stack. The call to longjmp(b_buf, 1)
is where things start to go wrong, because the stack frame referenced by b_buf
no longer exists after the longjmp(a_buf)
.
/ code>:
From the documentation for longjmp
:
在调用setjmp()例程返回的例程之后,可能不会调用longjmp
The longjmp() routines may not be called after the routine which called the setjmp() routines returns.
这包括通过 longjmp()
。
这篇关于SetJmp / LongJmp:为什么这会抛出segfault?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!