C++ new does not return 0 on failure!

This tip submitted by Are R. Svendsen on 2005-02-27 21:38:01. It has been viewed 131677 times.
Rating of 5.2 with 554 votes



C++ "new" does not return 0 ("NULL") on failure!

..unless you explicitly tell it not to thrown an exception by using std::nothrow (see Demonstration 2 on how to do this). The default behaviour for new is to throw an exception on failure. If a program does not expect (catch) the exception, it will be terminated when new fails (look up the try and catch keywords for more information on exceptions).

Demonstration 1 - How not to use "new"

The example below shows an erroneous program. Please compile it and run the program from the command-line. It demonstrates what happens when an exception goes uncaught, as in this case when we allocate more memory than the system is able to offer. What will happen here is that the program will be terminated instead of continuing its normal execution!
// Demonstration 1 - How not to use "new"

#include <iostream>

int signed main ();

int signed main ()
{
  int signed * pais;

  pais = new int signed [-1]; // error: exception not expected

  if (pais) pais[0] = 10;

  delete [] pais;

  std::cout << "Is this part reached?" << std::endl;

  return 0;
}
The error here is that the program does not expect new to throw an exception, neither does it explicitly tell new not to throw an exception, which brings us to the next demonstration. (Note that delete accepts the value 0, but in this example it is irrelevant, because program execution would never get this far.)

Demonstration 2 - Forcing "new" to return 0 ("NULL") on failure

If you want new to return 0 ("NULL") on failure, you have to explicitly tell it not to throw an exception. To do this, simply include the header "new", which defines the std::nothrow option, and then add "(std::nothrow)" as shown below.
// Demonstration 2 - Forcing "new" to return 0 ("NULL") on failure

#include <new>
#include <iostream>

int signed main ();

int signed main ()
{
  int signed * pais;

  pais = new (std::nothrow) int signed [-1]; // ok: exception never thrown

  if (pais) pais[0] = 10;

  delete [] pais;

  std::cout << "Is this part reached?" << std::endl;

  return 0;
}
Now the program works as the programmer expected! Note that delete accepts the value 0 ("NULL").

Document

  • Published: 2005-02-27
  • Copyright: None (Public Domain)
  • Author: Are R. Svendsen (Aremond)





More tips

Help your fellow programmers! Add a tip!