What is the difference between setjmp() and longjmp() in c++ i am confused
Upvotes: 0
Views: 1429
Reputation: 49
Treat longjump as a non local goto. You set a point to jump back using setjmp and jump back to it using longjmp. Read the following two links to understand it better
http://www.cppreference.com/wiki/c/other/setjmp
Also read about the longjmp to understand the usage.
Upvotes: 0
Reputation: 76531
Don't use setjmp/longjmp in C++. The problem is that setjmp/longjmp is a low level C API that does not properly handle stack unwinding. So, if you had code like this:
void dont_do_this(jmp_buf jmp)
{
std::string leakme("bad");
longjmp(jmp, leakme.length());
}
the string destructor will not be called and you'll leak memory.
It's possible even worse things can happen as this is undefined behavior. According to section 18.7/4:
The function signature longjmp(jmp_buf jbuf, int val) has more restricted behavior in this International 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.
Upvotes: 12