Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will new return NULL in any case?

I know that according to C++ standard in case the new fails to allocate memory it is supposed to throw std::bad_alloc exception. But I have heard that some compilers such as VC6 (or CRT implementation?) do not adhere to it. Is this true ? I am asking this because checking for NULL after each and every new statement makes code look very ugly.

like image 314
Naveen Avatar asked Feb 15 '09 07:02

Naveen


People also ask

Can new ever return NULL?

Unlike malloc(), new never returns NULL! However, if your compiler is ancient, it may not yet support this.

What does return NULL return?

Returning null is often a violation of the fail fast programming principle. The null can appear due to some issue in the application. The issue can even go to production if the developer has not implemented proper exception handling, which can help quickly detect the issue.

What does new operator returns on failure?

When the nothrow constant is passed as second parameter to operator new , operator new returns a null-pointer on failure instead of throwing a bad_alloc exception. nothrow_t is the type of constant nothrow . A pointer to an already-allocated memory block of the proper size.

What happens when new fails in C++?

By default, when the new operator is used to attempt to allocate memory and the handling function is unable to do so, a bad_alloc exception is thrown. But when nothrow is used as an argument for new, and it returns a null pointer instead.


1 Answers

VC6 was non-compliant by default in this regard. VC6's new returned 0 (or NULL).

Here's Microsoft's KB Article on this issue along with their suggested workaround using a custom new handler:

  • Operator new does not throw a bad_alloc exception on failure in Visual C++

If you have old code that was written for VC6 behavior, you can get that same behavior with newer MSVC compilers (something like 7.0 and later) by linking in a object file named nothrownew.obj. There's actually a fairly complicated set of rules in the 7.0 and 7.1 compilers (VS2002 and VS2003) to determine whether they defaulted to non-throwing or throwing new.

It seems that MS cleaned this up in 8.0 (VS2005)—now it always defaults to a throwing new unless you specifically link to nothrownew.obj.

Note that you can specify that you want new to return 0 instead of throwing std::bad_alloc using the std::nothrow parameter:

SomeType *p = new(std::nothrow) SomeType; 

This appears to work in VC6, so it could be a way to more or less mechanically fix the code to work the same with all compilers so you don't have to rework existing error handling.

like image 53
Michael Burr Avatar answered Sep 29 '22 07:09

Michael Burr