gpt4 book ai didi

c - 这个 setjmp/longjmp 上下文中的自动变量是什么?

转载 作者:太空狗 更新时间:2023-10-29 16:53:34 25 4
gpt4 key购买 nike

W. Richard Stevens 的《UNIX 环境中的高级编程》指出:

"What are the the states of the automatic variables and register variables in the main function?"

关于当您从堆栈下方的某处 longjmp 返回 main(或另一个函数)时会发生什么。

接着说:

"It depends. Most implementations do not try to roll back these automatic variables and register variables, but all that the standards say is that their values are indeterminate. If you have an automatic variable that you don't want rolled back, define it with the volatile attribute. Variables that are declared global or static are left alone when longjmp is executed.

他似乎是在说正常的堆栈变量不会将它们的值设置回 setjmp 时的值 - 但是在 longjmp 返回后函数的其余部分不能依赖其堆栈变量这看起来很疯狂,所以我猜我错了。

有人可以为我定义“自动变量”并解释具体是什么没有设置回其原始值以及为什么会这样吗?

最佳答案

它的意思是如果

  1. 您有一个未声明为 volatile 的自动(函数局部非静态)变量;和
  2. 您更改了 setjmplongjmp 之间的变量值

然后在 longjmp 之后,该变量的值变得不确定。

我认为这与此类变量驻留在 CPU 寄存器而非 RAM 中的可能性有关,以及在 longjmp 中保存此类变量值的相关困难。

这是来自 gcc manual 的引述:

If you use longjmp, beware of automatic variables. ISO C says that automatic variables that are not declared volatile have undefined values after a longjmp. And this is all GCC promises to do, because it is very difficult to restore register variables correctly, and one of GCC's features is that it can put variables in registers without your asking it to.

如果变量值的潜在丢失是您用例中的一个问题,请将相关变量声明为 volatile

关于c - 这个 setjmp/longjmp 上下文中的自动变量是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7271313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com