C++ Blog

Monday, April 02, 2007

When "new" fails?

When you create a object with new it allocates required memory for object, calls the constructor and returns a pointer to the created object.
If it fails to allocate contiguos memory, it calls a special pre-defined function called "new_handler" function, the default functionality of the function is to throw an exception, it throws an bad_alloc exception.
The user can override the defaul new_handler function using a "set_new_handler" function defined in new.h header file. The new handler function should take no arguments and return a void.

What if, I overload "new" operator?
When the user overloads the new operator it doesn't call new_handler by default. It is tied to the default behaviour of new operator, so when the user over loads the new the user should take care of calling this function.


What I can do in new-handler?
  • The user can write code to log and error message about the memory could not be allocated and then throw error, so that it might give enough ninformation to debug the program.
  • Even we can write a "garbage collector" in that function and try to re-claim the memory.


#include <iostream>
#include <new>
using namespace std;
int count = 0;
void out_of_memory()
{
cerr << "memory exhausted after " <<>
exit(1);
}
int main() {
set_new_handler(out_of_memory);
while(1) { count++; new int[1000]; // Exhausts memory }
} ///:~
********** Code sample from Thinking in C++ by Bruce Eckel *************

0 Comments:

Post a Comment

<< Home