Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

longjmp(buffer, 0) doesn't return 0

Tags:

c

setjmp

I'm trying to do something simple using setjmp/longjmp: asking a user to press Enter many times and if the user inserts something else it will restarts the process using longjmp.

I'm using a counter to check if it works, this counter is 0 at start but when longjmp is used the counter restarts at 1.

#include <stdio.h>
#include <setjmp.h>
jmp_buf buffer;
char inputBuffer[512];

void handle_interrupt(int signal) {
    longjmp(buffer, 0);
}

int main(int argc, const char * argv[]) {
    int counter = 0;
    counter = setjmp(buffer); // Save the initial state.

    printf("Counter: %d\n", counter);

    printf("\nWelcome in the jump game, press enter (nothing else!): \n");
    while (fgets(inputBuffer, sizeof(inputBuffer), stdin)) {
        if (*inputBuffer == '\n') { // If user press Enter
            counter++;
            printf("%d\n\n", counter);
            printf("Again: \n");
        } else {
            handle_interrupt(0);
        }
    }
}

Output:

pc3:Assignement 3 ArmandG$ ./tictockforever
Counter: 0

Welcome in the jump game, press enter (nothing else!): 

1

Again: 

2

Again: 
StackOverflow
Counter: 1

Welcome in the jump game, press enter (nothing else!): 

2

Again: 

I know that this code is silly, I'm just trying to use setjmp/longjmp on a simple example.

like image 282
Armand Grillet Avatar asked Apr 15 '26 05:04

Armand Grillet


2 Answers

setjmp only returns 0 when returning the first time, directly.

In any other cases, it returns whatever you passed to longjmp, unless you passed 0:
In that case it returns 1.

like image 70
Deduplicator Avatar answered Apr 16 '26 20:04

Deduplicator


You need to download a copy of the C Standard (Google for "C11 Draft Standard" for example) and read the documentation of setjmp / longjmp very, very carefully. setjmp is not a function like others. Your use of setjmp is absolutely illegal. About the only legal way to use it is something like

if (setjmp (...)) {
    ...
} else {
    ...
}
like image 45
gnasher729 Avatar answered Apr 16 '26 19:04

gnasher729



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!