Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to call 'longjmp' after a 'setjmp'

Tags:

c

setjmp

In the manpage on longjmp and setjmp, there's this line:

If the function which called setjmp() returns before longjmp() 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?

like image 549
Michail Avatar asked Dec 23 '17 20:12

Michail


1 Answers

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.

like image 137
Jean-François Fabre Avatar answered Sep 27 '22 19:09

Jean-François Fabre