Re: Program aborted; new doesn't return NULL

From: Victor Bazarov (v.Abazarov_at_comAcast.net)
Date: 01/17/05


Date: Mon, 17 Jan 2005 14:44:12 -0500

Alex Vinokur wrote:
> ------ foo.cpp ------
> #include <iostream>
> using namespace std;
>
> int main()
> {
> #define FACTOR 10
> for (unsigned long array_size = 1; ; array_size *= FACTOR)
> {
> int* p = new int[array_size];

If you want 'new' to return NULL instead of throwing an exception, use

     int* p = new (nothrow) int[array_size];

> // int* p = (int*)malloc (array_size * sizeof(int)); - works fine
>
> cerr << array_size << " : ";
>
> if (!(p == NULL))
> {
> cerr << "SUCCESS" << endl;
> delete p;
> }
> else
> {
> cerr << "FAILURE" << endl;
> break;
> }
> }
>
>
> return 0;
>
> }
> ---------------------
>
>
> --- Compilation & Run ---
>
> // g++ 3.3.3
>
> $ g++ -W -Wall foo.cpp
>
> $ a
>
> 1 : SUCCESS
> 10 : SUCCESS
> 100 : SUCCESS
> 1000 : SUCCESS
> 10000 : SUCCESS
> 100000 : SUCCESS
> 1000000 : SUCCESS
> 10000000 : SUCCESS
> 100000000 : SUCCESS
> Aborted (core dumped)
>
> -------------------------
>
> The program is aborted. Why doesn't the program print "FAILURE"?
> P.S. If we are using 'malloc' instead of 'new' the program does print "FAILURE".

'new' throws 'std::bad_alloc' on failure. RTFM.

Victor



Relevant Pages