Thread: Question about setjmp /longjmp

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    2

    Question about setjmp /longjmp

    Hi all I have a question about setjmp and longjmp
    suppose i have this code
    Code:
    #include <setjmp.h>
    jmp_buf buf1,buf2;
    
    void f2(){
     if(!setjmp(buf2)){
      longjmp(buf1,1);
     }
    }
    void f1(){
     if(!setjmp(buf1)){
      f2();
     }
      int x=0;
     if(!x){
      x=1;
      longjmp(buf2,1);   //error happens here
     }
    }
    int main(){
     f1();
     return 0;
    }

    This code has an error that when f1 called f2 then setjmp(buf2) made buf2 points to the stack position but when longjmp(buf1,1) is called it means f2 returned so it's position in stack is now garbage and the behavior of longjmp ( buf2,1) is now unpredictable .

    the solution to that is to save the entire stack and restoring it when returning to f2 again
    The question is how this can be done !!!???
    Last edited by hussein; 08-16-2009 at 02:02 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well what you posted won't even compile.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Aug 2009
    Posts
    2
    sorry here is the code and it compiles right
    Code:
    #include <setjmp.h>
    jmp_buf buf1,buf2;
    
    void f2(){
     if(!setjmp(buf2)){
      longjmp(buf1,1);
     }
    }
    void f1(){
     if(!setjmp(buf1)){
      f2();
     }
     longjmp(buf2,1);
    }
    
    int main(){
     f1();
     return 0;
    }
    it produces segmentation fault according to the problem i mentioned
    I posted the previous just to explain the problem ..sorry for that

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM