Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Safe to use longjmp and setjmp?

Is it safe to use longjmp and setjmp in C++ on linux/gcc with regards to the following?

  1. Exception handling (I'm not implementing exception handling using longjmp/setjmp. I want to know what side effects longjmp/setjmp will have on standard exception handling)
  2. *this pointer
  3. Signals
  4. Smart pointers (boost's shared and intrusive pointers)
  5. Anything else you can think of.
like image 613
jameszhao00 Avatar asked Sep 03 '09 21:09

jameszhao00


People also ask

Why use setjmp and longjmp?

setjmp saves the current environment (the program state), at some point of program execution, into a platform-specific data structure ( jmp_buf ) that can be used at some later point of program execution by longjmp to restore the program state to that saved by setjmp into jmp_buf .

What is the difference between Goto and long JMP and setjmp ()?

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 nonlocal, or far, jump of program execution.

Why use longjmp?

You may use longjmp() to get out of a signal handler, especially things like a BUS ERROR . This signal can not usually restart. An embedded application may wish to handle this case for safety and robust operation.

What does setjmp return?

The setjmp() function saves various information about the calling environment (typically, the stack pointer, the instruction pointer, possibly the values of other registers and the signal mask) in the buffer env for later use by longjmp(). In this case, setjmp() returns 0.


1 Answers

setjmp()/longjmp() completely subvert stack unwinding and therefore exception handling as well as RAII (destructors in general).

From 18.7/4 "Other runtime support" in the standard:

If any automatic objects would be destroyed by a thrown exception transferring control to another (destination) point in the program, then a call to longjmp(jbuf, val) at the throw point that transfers control to the same (destination) point has undefined behavior.

So the bottom line is that setjmp()/longjmp() do not play well in C++.

like image 137
Michael Burr Avatar answered Oct 14 '22 04:10

Michael Burr