Hi I want to ask about setjmp/longjmp. I tried to search, but I was unsucessuful...
#include <stdio.h>
#include <setjmp.h>
jmp_buf a, b;
void jump() {
int aa = setjmp(a);
if (aa)
{
printf("Jump!\n");
}
else
{
longjmp(b, 1);
printf("Should not happened...\n");
}
printf("End of function!\n");
}
int main(int argc, char** argv) {
int bb = setjmp(b);
if (bb)
{
longjmp(a, 1);
printf("Should not happened...\n");
}
else
{
jump();
printf("What here?\n");
}
printf("Exit\n");
return 0;
}
The question is, what will happen after last printf in jump()... I tried this code and it turned into infinite loop. Why? I though that setjmp will store environment data, so the jump function shall return after it's original call... I'm quiet confused. Thanks for reply :)
The whole program has undefined behavior.
setjmp(b);
stores the stack state.jump()
is called.longjmp(b, 1);
restores the stack to the point beforejump()
was ever called. So the state stored ina
is now invalid.if
inmain()
.longjmp(a, 1);
is called. Ouch. This causes undefined behavior due to 4 above.Your confusion probably results from the slightly imprecise use of the world "return" in the Linux docs for
setjmp()
.In your example, the function
jump()
didn't return in the normal way, but the effect was the same: the stack was "chopped" by the firstlongjmp()
to the state beforejump()
, which is what a return does, too.