Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!mcsun!ukc!edcastle!aiai!richard From: richard@aiai.ed.ac.uk (Richard Tobin) Newsgroups: comp.lang.c Subject: Re: Using setjmp/longjmp Message-ID: <2432@skye.ed.ac.uk> Date: 7 May 90 18:35:58 GMT References: <735@mwtech.UUCP> <0654@sheol.UUCP> Reply-To: richard@aiai.UUCP (Richard Tobin) Organization: AIAI, University of Edinburgh, Scotland Lines: 39 In article <0654@sheol.UUCP> throopw@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@uk.ac.ed AI Applications Institute, ARPA: R.Tobin%uk.ac.ed@nsfnet-relay.ac.uk Edinburgh University. UUCP: ...!ukc!ed.ac.uk!R.Tobin