Pontus Pihlgren wrote:
What is the safe thing to do after a longjmp to a
previous setjmp
position?
Jules Richardson wrote:
Dump core and run away? :-)
ben wrote:
Why the heck are you doing that?
A: Quit ... your code is toast.
If you guys really don't think that there's anything better to do than
that, why would you use bother to use setjmp() and longjmp()? You could
just exit().
Toby Thain wrote:
iirc, you would avoid using any auto (stack) variables
that were in
scope.
That's far more restrictive than actually necessary. You should avoid
accessing any automatic variables local to the function that invoked
setjmp() and not declared volatile and that may have changed between the
setjmp() invocation and longjmp(). In other words, an ordinary local
variable that is not changed after the setjmp() invocation can still be
used. In practice that means that the function invoking setjmp() should
usually not pass a pointer to that variable to another function that
might modify it before the longjmp(), or should declare it volatile if
it does.
Here's another test of how well you know proper use of
setjmp()/longjmp(). The C99 code below (which obviously is not valid
C89) has had some printf() calls inserted for debugging. What will this
program do? Hint: this is trickier than it looks. (If you're going to
look it up in the standard, don't post the answer. The question is how
well people know it, not whether they can read.)
Eric
// ---------------- cut here ----------------
#include <setjmp.h>
#include <stdio.h>
jmp_buf buf;
// trivial test of longjmp()
int foo (void)
{
printf ("in foo, before longjmp()\n");
longjmp (buf, 0);
printf ("in foo, after longjmp()\n");
}
// main program
int main (int argc, char**argv)
{
int a;
printf ("started main\n");
a = setjmp (buf);
printf ("setjmp() returned %d\n", a);
if (! a)
foo ();
else
printf ("longjmp() caused control to return to main\n");
printf ("main about to exit\n");
return 0;
}
// ---------------- end ----------------