Tuesday, February 26, 2008

What to do when your C++ memory underruns..

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.

Tuesday, February 19, 2008

The C++ Memory Free Store

It is a concept that is very conveniently skipped while learning C++ at the beginner's level. Having used the 'new' and 'delete' operators, it is imperative to understand how the C++ memory is managed.

1. What does the 'new' operator actually do??

Ans. It basically does two things - allocate memory for the new object and call the constructor of that object and thereby in effect 'create' the object.

The C++ Memory Heap a.k.a the 'free-store' is used to assign chunks of memory size as requested by each constructor that is called by the 'new' operator on that object.

In comparison to the malloc() function, the new operator returns a type-safe pointer while th malloc() return a pointer of type 'void' which needs to be explicity type-casted by the programmer.

For the special case when the memory store available with the free store is exhausted, we can test if the new operator returns a NULL.. But there is a more elegant way to handle this case.. look for my next post on how to handle the situation of free store exhuastion.