I was investigating setjmp/longjmp and found out that setjmp saves registers such as instruction pointer, stack pointer etc...
However what I don't get here is that, can't the data in the stack of the thread itself be modified between the call to setjmp and longjmp. In that case, wouldn't longjmp not work as expected.
To make it clear, for example, when longjmp restores the stack pointer, say the data in the memory the stack pointer is pointing now is not the same as was when setjmp was called. Can this happen? And if that happens, aren't we in trouble?
Also what is meant by the statement, "The longjmp() routines may not be called after the routine which called the setjmp() routines returns."
The stack pointer marks the division between the "used" and "unused" portions of the stack. When you call
setjmp
, all current call frames are on the "used" side, and any calls that take place aftersetjmp
, but before the function which calledsetjmp
returns, have their call frames on the "unused" side of the saved stack pointer. Note that callinglongjmp
after the function which calledsetjmp
has returned invokes undefined behavior, so that case does not need to be considered.Now, it's possible that local variables in some of the existing call frames are modified after
setjmp
, either by the calling function or through pointers, and this is one reason why it's necessary to usevolatile
in many cases...