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."
setjmp and longjmp are a pair of C function facilitating cross-procedure transfer of control. Typically they are used to allow resumption of execution at a known good point after an error. Both take as first argument a buffer, which is used to hold the machine state at the jump destination.
What is the difference between goto and longjmp() and setjmp() A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a non local, or far, jump of program execution.
The setjmp. h header file contains function declarations for longjmp() and setjmp() , which use the system stack to affect the program state. It also defines one buffer type, jmp_buf , that the setjmp() and longjmp() functions use to save and restore the program state. Parent topic: Header Files.
The jmp_buf type is an array type suitable for storing information to restore a calling environment. The stored information is sufficient to restore execution at the correct block of the program and invocation of that block.
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 after setjmp
, but before the function which called setjmp
returns, have their call frames on the "unused" side of the saved stack pointer. Note that calling longjmp
after the function which called setjmp
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 use volatile
in many cases...
setjmp()/longjmp()
are not meant to save the stack, that's what setcontext()/getcontext()
are for.
The standard specifies that the value of non-volatile automatic variables defined in the function that calls setjmp()
that are changed between the setjmp()
and the longjmp()
calls are unspecified after a longjmp()
. There are also some restrictions on how you call setjmp()
for this same reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With