Using setjmp/longjmp

Richard Tobin richard at aiai.ed.ac.uk
Tue May 8 04:35:58 AEST 1990


In article <0654 at sheol.UUCP> throopw at sheol.UUCP (Wayne Throop) writes:
>> [...] malloc [...] interferes with setjmp/longjmp
>Pardon?  In what way?

I think the poster meant that it's difficult to use longjmp() to abort
to your program's main loop and at the same time clean up memory
allocated "on the way down".

The problem is the lack of an "unwind-protect" function, which would cause
longjmp() to execute "clean-up" code as it unwinds the stack (which of
course it doesn't in most implementations).

It shouldn't be too hard to synthesise something like Lisp's
catch/throw/unwind-protect.  Catch would call setjmp() and push (a
pointer to) the jmp_buf onto a stack.  Unwind_protect would take a
function as an argument and push it onto the same stack with a marker
identifying it as an unwind_protect.  Throw would pop jmp_buf's off
the stack, calling any unwind-protect functions it came to, until it
reached the target jmp_buf, which it would then longjmp() to.

Actually, it might be more convenient to have the clean-up code not be
a function, but just some code in the function calling unwind_protect.
This could be accomplished by having unwind_protect do a setjmp(), and
having throw longjmp() to it.  The only difficulty is having the
unwinding be resumed after the clean-up code.  This could probably be
done with some horrible macro hack so that you could write

  unwind_protect {
     ... clean-up code ...
  }

If you also want it to do the clean-ups when a function returns, this
will be rather harder.

-- Richard
-- 
Richard Tobin,                       JANET: R.Tobin at uk.ac.ed             
AI Applications Institute,           ARPA:  R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University.                UUCP:  ...!ukc!ed.ac.uk!R.Tobin



More information about the Comp.lang.c mailing list