I do not understand why in the function middleFunc(), a segmentation fault is raisen when entry_point(arg) is invoked inside the if ( setjmp(middle) ) statement.
#include <stdio.h>
#include <setjmp.h>
jmp_buf start,middle,end;
void finalFunc(void *v)
{
printf("hello\n");
return ;
}
void middleFunc(void (*entry_point)(void *), void *arg)
{
//just debug : this does not cause segmentation fault
entry_point(arg);
if ( setjmp(middle) ){
//this casues the segmentation fault
entry_point(arg);
//once the entry point (finalFunc) is executed go to jmp_buffer end
longjmp(end,1);
}
else {
longjmp(start,1);
}
}
int main(){
if (setjmp(end)){
//exit since finalFunc has been executed
return 0;
}
if (setjmp(start)){
//the middleFunc has previously set the jmp_buffer middle
longjmp(middle,1);
}
else{
int x = 1;
middleFunc(finalFunc,(void*)&x);
}
}
In your code the behavior is undefined. You are not allowed to long-jump to
middleaftermiddleFuncfinished execution (either by normal completion or by anotherlongjmp).In your code
middleFuncsets upmiddleand after that immediately exits tomainby doinglongjmp(start,1). After that jumpmiddleis no longer valid. You are no longer allowed to jump tomiddlefrom anywhere.setjmp/longjmpmechanism only supports jumps up the call stack. You cannot do side-jumps or down-jumps. Only up-jumps are supported.From the practical point of view, you are attempting to jump into a "dead" function invocation and somehow expecting that function parameter values are still valid (like, preserved from the previous invocation or something). But they are not.
setjmp/longjmpdo not preserve/restore parameter values. Value ofentry_pointin that "dead" invocation is probably some garbage. When you attempt to make a call throughentry_point, the code coredumps.P.S. It is true that side-jumping with
setjmp/longjmpis sometimes used to implement co-routines. However, such usage falls outside the boundaries of standard library specification. And in any case such usage will never expect preservation of parameter values.