Wednesday 27 October 2010

'new operator' throw and nothrow

I used to always think and while coding take care that to check if memory allocation is successful, we need to check if the returned pointer is not NULL. Well, in MSVC8 this may not necessarily be true. Depending on the library you include (see here) you may end up with either a throw or a NULL. The partial good news is that you can in future write your code to not throw memory alloc failure. See example:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

int
main()
{

try

{

char
* p = new char[0x7fffffff];
if
(!p)
{

cout<<"Memory allocation for q failed. NULL returned."<<endl;
}
}

catch
(...)
{

cout<<"Exception caught by ..."<<endl;
}


char
* q = new (std::nothrow) char[0x7fffffff];
if
(!q)
{

cout<<"Memory allocation for q failed. NULL returned."<<endl;
}


return
0;
}




The output is as follows:

No comments:

Post a Comment