c++/801: 'new' operator aborts on failure instead of throwing exception

godless@haelos.cinternet.net godless@haelos.cinternet.net
Tue Nov 14 07:36:00 GMT 2000


>Number:         801
>Category:       c++
>Synopsis:       'new' operator aborts on failure instead of throwing exception
>Confidential:   no
>Severity:       serious
>Priority:       high
>Responsible:    unassigned
>State:          open
>Class:          wrong-code
>Submitter-Id:   net
>Arrival-Date:   Tue Nov 14 07:36:00 PST 2000
>Closed-Date:
>Last-Modified:
>Originator:     godless@haelos.cinternet.net
>Release:        pgcc-2.91.66
>Organization:
>Environment:

>Description:
Output of 'g++ -v':
	Reading specs from /usr/lib/gcc-lib/i686-pc-linux-gnu/pgcc-2.91.66/specs
	gcc version pgcc-2.91.66 19990314 (egcs-1.1.2 release)

Using this and other versions of G++, programs that use
the 'new' operator to allocate memory will be abort()ed if
no memory is available. The correct behavior is for the
'new' operator to throw an exception of type 'bad_alloc',
which can be caught by the program and handled in a more
intelligent way. 
>How-To-Repeat:
Compile and run a simple program that allocates too much memory
and catches exceptions:

// ALL of these should be available on a GNU/Linux system:

#include <limits.h>
#include <new>
#include <exception>
#include <iostream>
using std::cerr;

int main(int argc, char **argv) {
	char *string;

	try {
		// Allocate way more memory than is
		// available. This should throw an
		// exception, but instead, it aborts
		// the program.
		string = new char[(size_t)ULONG_MAX];
	} catch(bad_alloc) {
		std::cerr << "This code is never executed." << endl;
	} catch(...) {
		std::cerr << "Niether is this code." << endl;
	}

	delete string;
	return 0;
}
>Fix:

>Release-Note:
>Audit-Trail:
>Unformatted:


More information about the Gcc-bugs mailing list