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.


How To Get The Size Of Memory Allocated In Heap

September 20, 2008

sizeof() function can not give the size of memory locations allocated using new, malloc, calloc and realloc. VC++ provides a macro for the above purpose and it is _msize. See the following code segment.

#include
using namespace std;
int main()
{  
   // Allocate 10 integer locations 
   // = a toatl of 40 in 32 bit platforms
   int* pInt = new int[10];
   size_t Size = _msize(pInt);
   cout << Size << '\n';       return 0; } [/sourcecode] The result will be 40.