By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,300 Members | 1,867 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,300 IT Pros & Developers. It's quick & easy.

Program aborted; new doesn't return NULL

P: n/a
------ 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)

-------------------------

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".
--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn

Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Jul 22 '05 #2

P: n/a

"Victor Bazarov" <v.********@comAcast.net> wrote in message news:gA******************@newsread1.mlpsca01.us.to .verio.net...
[snip]
If you want 'new' to return NULL instead of throwing an exception, use

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


Indeed. Thanks.

[snip]

--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn

Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.