While playing with Pointers, the worst fears of any programmer are underruns and overflows....
But there is a very elegant solution to memory exhaustion in C++, wont provide you more memory but will at-least ensure that this exception is well handled..Here is the way out..
Suppose that your new operator used for creating new objects in the memory runs out of free memory so what to do then?
C++ has an internal function pointer called the _new_handler. Usually it contains a NULL which is returned by new operator when it fails to allocate memory for the requested object.
Now there is another special construct called the set_new_handler ( ) that lets you set the _new_handler to point to a user defined function which will be called in-case the new operator fails to allocate the memory. So that particular function will be called when such a case occurs.
Here is a code snippet to explain better:
void main( )
{
void outpfMemory( );
set_new_handler(outofMemory);
char *pointer = new char[..some large value like 64000u...];
}
void outofMemory( )
{
cout<<"OOPS Ran out of memory.."; exit(1); }
The function outofMemory will be called when the char Pointer assignment fails due to lack to available memory in the free store.
But there is a very elegant solution to memory exhaustion in C++, wont provide you more memory but will at-least ensure that this exception is well handled..Here is the way out..
Suppose that your new operator used for creating new objects in the memory runs out of free memory so what to do then?
C++ has an internal function pointer called the _new_handler. Usually it contains a NULL which is returned by new operator when it fails to allocate memory for the requested object.
Now there is another special construct called the set_new_handler ( ) that lets you set the _new_handler to point to a user defined function which will be called in-case the new operator fails to allocate the memory. So that particular function will be called when such a case occurs.
Here is a code snippet to explain better:
void main( )
{
void outpfMemory( );
set_new_handler(outofMemory);
char *pointer = new char[..some large value like 64000u...];
}
void outofMemory( )
{
cout<<"OOPS Ran out of memory.."; exit(1); }
The function outofMemory will be called when the char Pointer assignment fails due to lack to available memory in the free store.
Comments