-1

I am trying to create an infinite loop using those functions (unsuccessfully).

My code :

jmp_buf buf1;

void foo(){
    int z = 4, y = 1;
    int v = setjmp(buf1);
    if(v == 0){
     printf("A%d", z);
     longJmp(buf1, 1);
    }
    else if(v == 1){
        printf("B%d", y);
        longjmp(buf1,1);
    }
}

int main(){
    int v = setjmp(buf1);
    if( v == 0){
        printf("C%d", 1);
        foo();
        longjump(buf1,1);
    }
}

I thought it would print C1A4B1B1B1.... (B1 repeats forever) but I just get C1A4B1 and the program stops (SEGMENTATION ERROR). Isn't calling longJmp always return to setJmp with parameter val?

Would like to understand where is my mistake.

EDIT : The code I copied before I got answers is mistakenly incorrect, longjmp(buf1,2) instead of longjmp(buf1,1). Also I didn't copy the full main code which cause the seg fault. (another longjmp after foo being called)

Asurii
  • 69
  • 6
  • 2
    I recommend you learn how to use a *debugger* and how to use it to set *breakpoints*. Set a breakpoint on each `setjmp` call and see what value it returns each time it returns. – Some programmer dude Oct 10 '21 at 13:17
  • Also please create a proper [mre], one which will actually build (even after adding header files the shown code won't build). And then *copy-paste* it into your question. – Some programmer dude Oct 10 '21 at 13:18

1 Answers1

1

after line 15, longjmp(buf1,2);
v is 2.

When next repeat, v is not 1, function has end.

longjmp(buf1,2); > longjmp(buf1,1);

hyuckkim
  • 45
  • 5
  • There's no `longjmp(buf1,2)` in the code shown in the question. And line 15 is the empty line before the `main` function (unless my counting os off). – Some programmer dude Oct 10 '21 at 13:35
  • @Someprogrammerdude I mistakenly copied incorrect code, I'll be sure paying more attention next time before asking a question. much apologies. – Asurii Oct 10 '21 at 14:02