SetJmp/LongJmp:为什么会抛出段错误?

SetJmp/LongJmp: Why is this throwing a segfault?(SetJmp/LongJmp:为什么会抛出段错误?)

本文介绍了SetJmp/LongJmp:为什么会抛出段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码总结了我目前遇到的问题.我当前的执行流程如下,我在 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 返回后立即创建了一个段错误.几乎就好像只有 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(a_buf) 之后不再存在.

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

来自 longjmp 的文档:

在调用 setjmp() 例程的例程返回后,不能调用 longjmp() 例程.

The longjmp() routines may not be called after the routine which called the setjmp() routines returns.

这包括通过longjmp()从函数中返回".

This includes "returning" through a longjmp() out of the function.

这篇关于SetJmp/LongJmp:为什么会抛出段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:SetJmp/LongJmp:为什么会抛出段错误?

基础教程推荐