How To Handle new Operator Failure

January 15, 2009

new operator is used to allocate memory in C++. Though it is rare that a modern day computer is not able to allocate memory for our program, still there may be situations where we have to face situations where the new operator fails. The function set_new_handler will divert the flow to a user function when the new operator fails. A simple example is given below.

#include
using namespace std;

// Function to be called when the new operator fails
void NewHandler()
{
   cout << "Out of memory" << '\n';    exit(0); }   int main() {    // Set the function to be called when new operator fails    set_new_handler(NewHandler);    while (true)    {       new int[50000000];   // Hope this will fail after a few iterations       cout << "Successful so far" << '\n';    }    return 0; } [/sourcecode] In the above example, the function NewHandler() will be called when the memory allocation using new operator fails.

Some Background Info

set_new_handler will store the function NewHandler() in a static new handler pointer. This new handler is used by operator new.

Advertisements