Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will new operator return NULL? [duplicate]

Possible Duplicate:
Will new return NULL in any case?

Say i have a class Car and i create an object

Car *newcar  = new Car();
if(newcar==NULL) //is it valid to check for NULL if new runs out of memory
{
}
like image 391
ckv Avatar asked Aug 02 '10 15:08

ckv


People also ask

What does operator new return?

Operator new returns a pointer to a beginning of an array. Pointer is the address of some cell in memory. that's why we can say: Operator new returns a address to a beginning of an array.

What does new operator returns on failure?

If the new operator fails to allocate memory it returns NULL which can be used to detect failure or success of new operator.

What happens when new fails C++?

Answer: When we allocate memory from heap dynamically in a C++ program using new operator, the program crashes when memory is not available, or the system is not able to allocate memory to a program, as it throws an exception. So, to prevent program crash, we need to handle the exception when memory allocation fails.


3 Answers

On a standards-conforming C++ implementation, no. 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).

On some older C++ compilers (especially those that were released before the language was standardized) or in situations where exceptions are explicitly disabled (for example, perhaps some compilers for embedded systems), new may return NULL on failure. Compilers that do this do not conform to the C++ standard.

like image 189
James McNellis Avatar answered Oct 05 '22 12:10

James McNellis


No, new throws std::bad_alloc on allocation failure. Use new(std::nothrow) Car instead if you don't want exceptions.

like image 37
Georg Fritzsche Avatar answered Oct 05 '22 12:10

Georg Fritzsche


By default C++ throws a std::bad_alloc exception when the new operator fails. Therefore the check for NULL is not needed unless you explicitly disabled exception usage.

like image 34
Karel Petranek Avatar answered Oct 05 '22 13:10

Karel Petranek