Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it useful to test the return of "new" in C++?

I usually never see test for new in C++ and I was wondering why.

Foo *f = new Foo;

// f is assumed as allocated, why usually, nobody test the return of new?

like image 584
Guid Avatar asked Oct 27 '08 08:10

Guid


People also ask

What does new return in C?

new int is a new expression. The language defines that it returns an int* . Among other things it also calls the new operator, which, yes, returns a void* , because it just allocates raw storage. The constructor (empty for int ) turns raw storage into an initialized object.

Does new operator return NULL?

The ordinary form of new will never return NULL ; if allocation fails, a std::bad_alloc exception will be thrown (the new (nothrow) form does not throw exceptions, and will return NULL if allocation fails).

What happens if new fails to allocate memory?

In the above example, if new fails to allocate memory, it will return a null pointer instead of the address of the allocated memory. Note that if you then attempt indirection through this pointer, undefined behavior will result (most likely, your program will crash).

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.


1 Answers

As per the current standard, new never returns NULL, it throws a std::bad_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with "(std::nothrow)". i.e.

Foo* foo = new (std::nothrow) Foo; 

Of course, if you have a very old or possibly broken toolchain it might not follow the standard.

like image 91
David Holm Avatar answered Oct 13 '22 01:10

David Holm