Search code examples
csetjmp

failure of setjmp/longjmp


a piece of code here

jmp_buf mark;
int Sub_Func()  
{  
    int be_modify, jmpret;    
    be_modify = 0;    
    jmpret = setjmp( mark );  
    if( jmpret == 0 )  
    {  
        // sth else here 
    }  
    else  
    {  
        // error handle 
        switch (jmpret)  
        {  
            case 1:  
                printf( "Error 1\n");  
                break;  
            case 2:  
                printf( "Error 2\n");  
                break;  
            case 3:  
                printf( "Error 3\n");  
                break;  
            default :  
                printf( "Unknown Error");  
                break;  
        }  
        printf("after switch\n");        
    }     
    return jmpret;  
}  

void main( void )  
{  
    Sub_Func();   
    // the longjmp after setjmp
    longjmp(mark, 1);  
}  

the result is:
Error 1
after switch
Segmentation fault

I know the reason maybe longjmp jump back to the previous stack. but I'm not sure about the detail, and what kind of value has been stored in 'mark', can anyone explain that?


Solution

  • setjmp() and longjmp() work by recording a stack frame position. If you record the stack frame in Sub_Func() but return from the function before calling longjmp(), the stack frame is no more valid. longjmp() is meant to be called in the same function than setjmp() (subfunction is ok).