Mixing C, C++ and exceptions

Alastair Houghton alastair at alastairs-place.net
Mon Aug 20 17:32:49 PDT 2007


On 20 Aug 2007, at 11:35, Uli Kusterer wrote:

>  THE QUESTION: If I'm mixing C and C++ code compiled as separate  
> units (i.e. some in .c and some in .cpp files), is it safe for the C 
> ++ code to throw exceptions "through" the C++ code,

(I take it you mean to say "'through' the C code" here)

> ABI-wise? Will the stack get unrolled OK and all that?

Yes, aside from the problems you mention below.  However, in the case  
of C code, there's no real unwinding to do anyway...

> I'm not talking about problems I might be getting with the C code  
> leaking memory or not releasing resources it's acquired before the  
> exception happened, I'm aware that this will happen when an  
> exception happens before clean-up, but apart from that, does it work?

There are a few other problems besides the ones you mention.  The C  
code could leave something in an invalid state, rather than just  
leaking memory (in the same way that a C++ function written without  
RAII and exception handling might do the same if you throw through it).

As a result, it's generally regarded as a bad idea to throw through C  
code unless you know what the C code does.  Even then, you'd better  
be pretty sure that nobody is going to change it in the future in  
such a way that it will break when you throw through it.

> And while we're at it, can anyone confirm/deny that the same does  
> NOT apply to Objective C exceptions? Since they use longjmp under  
> the hood, they won't unroll the stack correctly, right?

That's not true.  They won't interact with C++ exception handling  
properly (except on Windows, where Microsoft implemented setjmp() and  
longjmp() in an odd manner), but they unwind the stack to the same  
extent that C++ code unwinds the stack for C functions.

(AFAIK, unwinding the stack for a C function really just means  
setting the stack pointer to a higher address.  It's that simple, and  
that's why exception handling can be implemented with setjmp() and  
longjmp().  Indeed, GCC used to do exactly that on some platforms...)

Kind regards,

Alastair.

--
http://alastairs-place.net





More information about the MacOSX-dev mailing list