Use set_new_handler to specify that your Handler should be called on memory allocation failure - C++ Class

C++ examples for Class:Exception Class

Description

Use set_new_handler to specify that your Handler should be called on memory allocation failure

Demo Code

#include <cstdlib>
#include <iostream>
#include <new>

// handle memory allocation failure
void customNewHandler() {
    std::cerr << "customNewHandler was called";
    abort();/* w  w  w  .j a  v a 2s  .c  o m*/
}

int main(int argc, const char *argv[]) {
    double *ptr[50];

    // specify that customNewHandler should be called on memory allocation failure
    std::set_new_handler(customNewHandler);

    for (int i = 0; i < 50; ++i) {
        ptr[i] = new double[50000000];
        std::cout << "ptr[" << i << "] points to 50,000,000 new doubles\n";
    }

    return 0;
}

Result


Related Tutorials