The subject of your post is "throwing out of memory exception in c++
doesn't work", but you've done precisely what it takes to /prevent/ such an
exception from ever being thrown: you've created and installed a
new_handler that doesn't follow the rules of what a new_handler should do,
which is one of the following ( I'm plagiarizing this from Dinkumware's C++
Reference):
make more storage available for allocation and then return
call either abort() or exit(int)
throw an object of type bad_alloc
If you've got a reasonably healthy quantity of virtual memory available,
though, it may take quite a while to thrash itself to exhaustion before it
reaches the point of calling your new_handler, so let's speed things up a
bit and add some exception handling:
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
void out_of_mem() {
cerr << "in out_of_mem: problem\n";
throw bad_alloc();
}
int main() {
set_new_handler(out_of_mem);
try {
while(1) {
cout << "Top of loop" << endl;
int * tst = new int[800000000]; // make this too much!
if (!tst)
cout << "end of loop: problem\n";
}
}
catch (const exception &e)
{
cerr << "Caught: " << e.what() << endl;
exit(1);
}
return 0; // not likely to get here!
}
Output (MSVC 7.1):
Top of loop
in out_of_mem: problem
Caught: bad allocation
So after you "handle" the exceptions and make sure your new_handler does
one of the right things, you'll still have the virtual memory thrashing
problem to contend with. I can't help you there, but you definitely want to
do a better job of avoiding memory leaks than your test program did (yeah
yeah, just kidding), and perhaps just "know" how much memory you can
allocate before the thrashing commences and try to keep track of what
you've allocated.
Good luck,
-leor
Leor Zolman
BD Software
(e-mail address removed)
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at
www.bdsoft.com/tools/stlfilt.html