1

I understand that setjmp saves the content of the registers (sp,fp,pc) so that longjmp can restore them later. And when longjmp is called, it makes (kind of) setjmp return the passed ret val. However, in the below program, I am little confused with the flow.

1  #include <setjmp.h>
2  #include <stdio.h>
3 
4  jmp_buf env;
5 
6  void hello()
7  {
8         int ret = setjmp(env);
9         if(ret != 0)
10        {
11                printf("error\n");
12        }
13        printf("hello called\n");
14 }
15
16 int main() {
17        printf("hello main\n");
18        hello();
19        printf("after hello call\n");
20        longjmp(env,1);
21        printf("after long jump\n");
22        return 0;
23 }

Output (I was not expecting this)
---------------------------------
hello main
hello called
after hello call
error
hello called

I was expecting an endless loop here, because when longjmp gets called, the ret in hello should be 1 (which is as per output) but then, once hello() has returned at this point, I should have again fallen at line 19 and hence again calling longjmp at line 20. Please help me understand the behaviour here.

Naveen
  • 7,944
  • 12
  • 78
  • 165
  • Pretty sure that it's UB to call `longjmp` after `hello` has returned to `main`. – user3386109 Sep 01 '21 at 04:04
  • 1
    This is undefined behavior; since the `setjmp` was done inside `hello`, you aren't allowed to `longjmp` there after `hello` has returned. The idea is that `longjmp` is only supposed to go up the call stack. – Nate Eldredge Sep 01 '21 at 04:05
  • 1
    Does this answer your question? [SetJmp/LongJmp: Why is this throwing a segfault?](https://stackoverflow.com/questions/1381937/setjmp-longjmp-why-is-this-throwing-a-segfault) – Jorengarenar Sep 01 '21 at 04:05
  • @Jorengarenar Yes it does. Thanks. – Naveen Sep 01 '21 at 05:28

0 Answers0