keith@csli.Stanford.EDU (Keith Nishihara) (03/08/90)
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