I've read various things about how one should not allocate heap memory in one DLL and deallocate it from outside that DLL. But what about throwing an exception object that is a just a temporary (as most exception objects are)? E.g.:
throw my_exception( args ); // temporary: no heap allocation
When the exception object is caught outside the DLL, the destructor for that object will eventually be executed and the non-heap memory for the object will be reclaimed. Is that OK since it's not heap memory?
C doesn't support exceptions. You can try compiling your C code as C++ with Visual Studio or G++ and see if it'll compile as-is. Most C applications will compile as C++ without major changes, and you can then use the try... catch syntax.
Explanation: As the func() is throwing a const char* string but we the catch block is not catching any const char* exception i.e. exception thrown is not handled therefore the program results into Aborted(core dumped).
An exception in C++ is thrown by using the throw keyword from inside the try block. The throw keyword allows the programmer to define custom exceptions. Exception handlers in C++ are declared with the catch keyword, which is placed immediately after the try block.
Throwing C++ exceptions across DLL boundaries is only possible when all modules use the same C++ runtime, in which case they share a heap as well. But this can be a maintenance burden, especially when libraries from multiple vendors are involved, so it is discouraged.
If you want error-handling which is portable across multiple compilers/compiler versions/compiler settings, either use return codes or OS-provided exceptions (e.g. SEH on Windows)/
It depends how that memory was allocated and whether the mechanism to do so ("the runtime" or "memory manager") is shared between the specific DLL and the other parts of the application. E.g. a throw new my_exception( args );
could also be in order depending on the details.
You could make your exception reference counted, so that it comes with the intrinsic knowledge of how to destroy its own instance (and owned memory).
Using IMalloc
(see MSDN) for instance allocation and placement new
would be another way (call OleInitialize
before) ...
Indeed, the memory allocation is an issue depending on what is being used. For example mixing statically linked CRT and dynamically linked CRT in different parts of an application will lead to issues the same way the mixing debug and release code would. The problem here is that the code that is supposed to free the memory uses a different "memory manager". But if the thrown object knows about its own destruction, it should be fine, since the dtor code would reside in the same compilation unit as the one allocating it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With