Topic: [Q] Confusion about operator new().
Author: kuhlins@hawk.wifo.uni-mannheim.de (Stefan Kuhlins)
Date: 18 Oct 1994 15:52:23 GMT Raw View
What's the right way to handle situations
where programs run out of memory?
Thanks in advance for every answer.
Stefan Kuhlins
PS: Here are the "facts" and a little testprogram:
ARM r.12.5
If operator new() cannot allocate storage it will return 0.
WP r.3.6.3.1 [basic.stc.dynamic.allocation] (3, 4)
If an allocation function is unable to obtain an appropriate block of
storage, it may invoke the currently installed new_handler and/or
throw an exception of class alloc or a class derived from alloc.
If the allocation function returns the null pointer the result is
implementation defined.
WP r.5.3.4 [expr.new] (17)
The allocation function may indicate failure by throwing an `alloc'
exception.
I tested this with a little program (see below) and several compilers.
Caution: Compiled with Borland C++ 1.5 for OS/2 the program stops the
-------- whole system!
#include <iostream.h>
#include <new.h>
#include <stdlib.h>
#include <except.h> // xalloc
void myhandler() {
cerr << "My Handler" << endl;
exit(1);
}
int main() {
// To be compatible with old programs:
// set_new_handler(0);
// Install your own handler and every system should have the same behavior:
// set_new_handler(myhandler);
// Handle the exception, if your compiler has exception handling
// and you know the name of the class thrown:
// try {
for (;;) {
if ((new double[10000])==0) { // the old way
cerr << "No memory!" << endl;
return 1;
}
else
cout << '.';
}
// } catch(xalloc) {
// cout << "Exception!" << endl;
// }
return 0;
}