diff --git a/src/init.cpp b/src/init.cpp index 7893afab9..852fd8b50 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -723,6 +723,19 @@ bool AppInitServers(boost::thread_group& threadGroup) return true; } +[[noreturn]] static void new_handler_terminate() +{ + // Rather than throwing std::bad-alloc if allocation fails, terminate + // immediately to (try to) avoid chain corruption. + // Since LogPrintf may itself allocate memory, set the handler directly + // to terminate first. + std::set_new_handler(std::terminate); + LogPrintf("Error: Out of memory. Terminating.\n"); + + // The log was successful, terminate now. + std::terminate(); +}; + /** Initialize bitcoin. * @pre Parameters should be parsed and config file should be read. */ @@ -784,6 +797,8 @@ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) signal(SIGPIPE, SIG_IGN); #endif + std::set_new_handler(new_handler_terminate); + // ********************************************************* Step 2: parameter interactions const CChainParams& chainparams = Params();