Advanced Programming in the UNIX Environment by W. Richard Stevens states:
“What are the the states of the automatic variables and register
variables in the main function?”
with regard to what happens when you longjmp back to main (or another function) from somewhere lower down the stack.
It goes on to say:
“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
volatileattribute. Variables that are declared global or static
are left alone whenlongjmpis executed.
It seems like he’s saying that normal stack-variables will not have their values set back to what they were at the time of the setjmp – but then the rest of the function couldn’t rely on its stack variables after the longjmp back to it which seems crazy, so I’m guessing I’m wrong.
Can someone define “automatic variables” for me and explain what specifically isn’t set back to its original value and why that is?
All it’s saying is that if
volatile; andsetjmpandlongjmpthen after the
longjmpthe value of that variable becomes indeterminate.I believe this has to do with the possibility of such variables residing in CPU registers rather than in RAM, and the associated difficulty of preserving the values of such variable across the
longjmp.Here is a quote from the
gccmanual:If the potential loss of variable values is a problem in your use case, declare the relevant variables as
volatile.