In the manpage on longjmp
and setjmp
, there's this line:
If the function which called
setjmp()
returns beforelongjmp()
is called, the behaviour is undefined.
Does that mean that I actually must call longjmp
somewhere in the function that called setjmp
or in a nested function? Or is it OK to not call it at all?
You're reading wrong.
If the function which called setjmp() returns before longjmp() is called, the behaviour is undefined.
The behaviour of longjmp
is undefined if you call it after you returned from the function which set the setjmp
. But it's perfectly all right not to call longjmp
at all.
Wikipedia is clearer:
If the function in which setjmp was called returns, it is no longer possible to safely use longjmp with the corresponding jmp_buf object.
This is because the stack frame is invalidated when the function returns. Calling longjmp restores the stack pointer, which—because the function returned—would point to a non-existent and potentially overwritten or corrupted stack frame.
Those functions are often used to handle exception mechanisms. If the exception doesn't occur, you don't want to call longjmp
because there's no reason to "rewind" your program.
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