Search code examples
c++exceptionbad-alloc

How to achieve, that bad-alloc aborts instead of throwing an exception


In our application, we log any crashes into a log file with stack trace included. We can use these reports to identify crash causes.

The problem is, that we tend to catch std::exception on several places (a lot actually), which makes the report effectively useless when bad_alloc is thrown, as the stack trace is lost.

How to change the behaviour, so instead of throwing bad_alloc, the program aborts? As we write in 3 different operating systems, so 3 different std implementations are used, changing the std itself is something we would like to avoid.


Solution

  • Besides a rethink or redesign to catch more tailored exceptions (which I really recommend) you have two solutions:

    1. Use the "no-throw" variants of operator new and operator new[]. Check for a returned null pointer, and abort.

    2. Set a new handler that calls std::terminate.