Search code examples
c++setjmp

stating jmp_buf as pointer


I'm tring to define jmp_buf as pointer and using it in nested longjmp(s).as follow:

 ...
jmp_buf *bfj;
...

and then writing if else:

if( setjmp(*bfj) == 0){
DS[SP-2].int_val=(int)bfj;;
//to store the bfj
}else {}

and somewhere else using the stored bfj to longjmp

 bfj = (jmp_buf *)DS[TOP].int_val;
 longjmp(*bfj,1);

where DS[TOP].int_val is where I stored it. as it may seems clear,I want to do nested gotos and returns using stored bfj. but well when I try to debug I get "unhandeled exception". I get this at the very starting point:

if( setjmp(*bfj) == 0)

I would be pleased if someone would tell the solution.


Solution

  • From your code, you are not actually allocating memory for your jmp_buf. There are a couple of things you can do:

    1. Dynamically allocate your jmp_buf with new and you will want to delete it when you are done with it
    2. Put the jmp_buf on the stack jmp_buf bfj; and when you want it's pointer, you would take it's address with &bfj.

    So, #1 would look like:

    jmp_buf *bfj = new jmp_buf;
    ...
    
    if( setjmp(*bfj) == 0){
    DS[SP-2].int_val=(intptr_t)bfj;
    

    while #2 would look like:

    jmp_buf bfj;
    ...
    
    if( setjmp(bfj) == 0){
    DS[SP-2].int_val=(intptr_t)&bfj;
    

    Another potential issue is that you should never cast a pointer to an int as a pointer may take more memory then an int (this happens on the common 64 bit programming models). If you can't store the pointer directly, you should use intptr_t instead.