How to check new operator() memory allocation failed with  set_new_handler

In C, when we allocate memory using functions malloc() or calloc() in addition, a NULL pointer will be returned if there is not enough space in the system to allocate

In C, we always make sure that the system has enough memory before the program crashes by using the below code

ptr = (int*)malloc(n * sizeof(int));
if(ptr==NULL)
{
printf("\n memory could not be allocated");
exit(0);
}

Similarly, we can do the same job in C++ by simply testing each use of the new operator() for a NULL

The new return a null pointer if it is unable to allocate memory

In C++, we have a function named set_new_handler that lets you set the _new_handler function pointer when the new operator() can’t allocate memory then the function being pointed to by _new_handler gets called

#include <iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    void memwarning();
    set_new_handler(memwarning);
     int *p=new int[1000000000000000];
     cout<<"enter the numbers";
     for(int i=0;i<1000000000000000;i++)
     {
         cin>>p[i];
     }
     cout<<" the number's are";
     for(int i=0;i<1000000000000000;i++)
     {
         cout<<"\n"<<p[i];
     }
     delete []p;
    set_new_handler(0);
    return 0;
}
void memwarning()
{
    cout<<endl<<"Memory allocation failed";
    exit(1);
}

As you might notice, the array size[1000000000000000] is intentionally taken too large so that you can see the memwarning() function creates a warning when there is no free space left to allocate

Mohammed Anees

Hey there, welcome to aneescraftsmanship I am Mohammed Anees an independent developer/blogger. I like to share and discuss the craft with others plus the things which I have learned because I believe that through discussion and sharing a new world opens up

Leave a Reply

Your email address will not be published.