Wednesday, March 5, 2008

new never returns NULL

Recently I gave the Brainbench c++ test and came across an interesting question.

It was something like:

{
int *i = new int[10];
if(!i)
{
NoMemoryHandler();
}
}


In this question, the right answer is "NoMemoryHandler() is never called".

Thats because, in c++ new operator never returns a NULL. In case of failure new simply throws an exception std::bad_alloc.

Now if you catch the exception and handle the situation, then its fine. Otherwise, if you don't catch the exception, your lovely program will get terminated. (Thats so uncool!)

Now everytime whenever you gotta write code, it should be like:

{
try
{
int *i = new int[10];
}
catch(bad_alloc &e)
{
cout << "OK, new failed!! But on the positive side, I am aware of it !!" << endl;
}
}

Fortunately to our rescue there is another version of new which doesn't throw anything on failing.

With reference to GCC's online docs we come to know about the nothrow version of new.

{
int *i = new (nothrow) int[10];
if(!i)
{
cout << "new failed!! but now I am not a slave of exceptions !!" << endl;
}
}

When I use the standard version of new, I have to handle the exception it throws on failure, else my program gets terminated.
If I use the "nothrow" version of new, I still need to write some healing code, but then I am free of unnecessary try{} and catch(){} blocks.

Until and unless I have to customize "new" for specific needs, I would always prefer the "nothrow" verison.

-----------------------------------------------------------------------
And yeah... I got a 4.69 score. Transcript id: 7416277.

2 comments:

Ankur said...

Loads of folks who come from C into C++ have a habit of checking for NULL. Nice post.

Shobhit said...

Nice to point out that C guys tend to make that mistake.
I never had thought that way.
Thanks leaving the first comment on my Blog.