Caveats and Limitations
When a "non-local goto" is executed via setjmp
/longjmp
, normal "stack unwinding" does not occur and therefore, any required cleanup actions such as closing file descriptors, flushing buffers, freeing heap-allocated memory, etc., do not occur.
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/corrupted stack frame.
Similarly, C99 does not require that longjmp
preserve the current stack frame. This means that jumping into a function which was exited via a call to longjmp
is undefined. However, most implementations of longjmp
leave the stack frame intact, allowing setjmp
and longjmp
to be used to jump back-and-forth between two or more functions—a feature exploited for multitasking.
Compared to mechanisms in higher-level programming languages such as Python, Java, C++, C#, and even pre-C languages such as Algol 60, the technique of using setjmp
/longjmp
to implement an exception mechanism is cumbersome. These languages provide more powerful exception handling techniques, while languages such as Scheme, Smalltalk, and Haskell provide even more general continuation-handling constructs.
Read more about this topic: Setjmp.h
Famous quotes containing the word limitations:
“No man could bring himself to reveal his true character, and, above all, his true limitations as a citizen and a Christian, his true meannesses, his true imbecilities, to his friends, or even to his wife. Honest autobiography is therefore a contradiction in terms: the moment a man considers himself, even in petto, he tries to gild and fresco himself.”
—H.L. (Henry Lewis)