Next: Enforcing Compile-time Constraints
Up: C++/C
Previous: stream format
setjmp
Although in this silly little demo the call to longjmp is in the same file
as the call to setjmp, this does not have to be the case, and in the practical
situation the call to longjmp will be a long way from the call to setjmp. The
mechanism is that setjmp saves the entire state of the computer's CPU in a
buffer declared in the jmp_buf save; statement and longjmp restores it exactly
with the exception of the register which carries the return value from longjmp.
This value is the same as the second argument in the longjmp call - i in our
little demo. This means, of course, that the stack and frame pointer registers
are reset to the old values and all the local variables being used at the time
of the longjmp call are going to be lost forever. One consequence of this is
that any pointer to memory allocated from the heap will also be lost, and
you will be unable to access the data stored in the buffer. This is what the
jargonauts call "memory leakage", and is really very difficult bug to find.
Your program runs out of dynamic memory long before it should. Take care.
So you have to keep a record of the buffers' addresses and free them
before the call to longjmp.
#include <setjmp.h>
#include <stdio.h>
jmp_buf x;
class FFFF
{
public:
~FFFF()
{printf("kill me\n");}
};
void f(int* g)
{
*g = 66;
printf("foo");
longjmp(x,5);
}
void foo(int* g)
{
f(g);
}
void bar(int* g)
{
FFFF f;
foo(g);
}
int main()
{
int i = 0;
int g = 99;
i = setjmp(x);
printf("%d\n",g);
if (i == 0)
{
bar(&g);
}
else
{
switch( i )
{
case 1:
case 2:
default: fprintf( stdout, "error code = %d\n", i); break;
}
}
return 0;
}
Return from a deep recursive
More
Next: Enforcing Compile-time Constraints
Up: C++/C
Previous: stream format
Wei Lu
2007-11-06