Program aborted; new doesn't return NULL

A

Alex Vinokur

------ 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];
// 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)
 
V

Victor Bazarov

Alex said:
------ 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)

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

Victor
 
A

Alex Vinokur

Victor Bazarov said:
If you want 'new' to return NULL instead of throwing an exception, use

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

Indeed. Thanks.

[snip]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top