Xref: utzoo comp.lang.c++:6737 gnu.g++:699 Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!usc!ucsd!ucbvax!decwrl!shelby!csli!keith From: keith@csli.Stanford.EDU (Keith Nishihara) Newsgroups: comp.lang.c++,gnu.g++ Subject: Recovering when out of memory. Keywords: new_handler Message-ID: <12586@csli.Stanford.EDU> Date: 8 Mar 90 02:09:37 GMT Sender: keith@csli.Stanford.EDU (Keith Nishihara) Reply-To: Neil Hunt Followup-To: comp.lang.c++ Organization: Center for the Study of Language and Information, Stanford U. Lines: 62 Can anyone send me an example of a new_handler function which re- covers so that the new, which exhausted memory, is able to return with a valid pointer. The kind of thing I have in mind is a new_handler which initially allocates a chunk of memory large enough to allocate the largest objects which might be needed, and holds it in reserve. When a new failure occurs, the reserve is deleted back into the free store, allowing the new to return nor- mally. Of course, warning flags and messages will be set and is- sued, so that the user knows to do something about the situation. Ideally, a solution portable to cfront 2.0 and g++ is desired! I tried the obvious thing in g++, just deleting a large object from an installed new_handler. Although the delete call is made, no new memory is returned: static char *large = 0; void my_new_handler() { if(large) { fprintf(stderr, "Freeing large\n"); delete large; large = 0; } else { fprintf(stderr, "Handler fails\n"); exit(-1); } } main() { __new_handler = my_new_handler; large = new char[1000000]; for( ; ; ) fprintf(stderr, "new at %x\n", new char[100000]); } new at 12751000 new at 12772000 new at 12793000 new at 127b4000 new at 127d5000 out of swap space, pid 8655, proc k Freeing large new at 0 out of swap space, pid 8655, proc k Handler fails Note that although I deleted 1M of space, (`Freeing large'), the call to new which invoked the new_handler returns 0 (`new at 0'), and the next call to allocate 100k of space still finds no memory and the new_handler is called again, this time exiting (`Handler fails'). Neil/. Neil%teleos.com@ai.sri.com