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

2023-04-12C/C++开发问题
1

本文介绍了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:为什么会抛出段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6