Path: utzoo!attcan!uunet!snorkelwacker!usc!sdd.hp.com!hplabs!hpcc01!hpccc!burch From: burch@hpccc.HP.COM (Jeff Burch) Newsgroups: comp.lang.c++ Subject: Re: Failed allocation in constructors? Message-ID: <5880004@hpccc.HP.COM> Date: 13 Jul 90 15:08:30 GMT References: <9075@goofy.Apple.COM> Organization: HP Corp Computing & Services Lines: 56 A feature of C++ that I just discovered may be helpful. Operator new has a built in mechanism that will check if memory allocation fails. It will automatically call a user supplied routine. Consequently, you can deal with this condition in one place and not have to check for NULL's in your code. For instance, without this feature, you should do this: void foo() { char *pnt = new char[ 123456789]; if (pnt == NULL) { // oops! ... } } With this feature, you can skip the error checking. To enable it, do this somewhere (probably in main()): #include main() { void free_store_exception( void); // your routine // catch memory allocation failures: set_new_handler( free_store_exception); ... } void free_store_exception( void) { // Oops, memory allocation has failed! fprintf(stderr,"Major bomb, out of memory!\n"); // What you choose to do at this point is wide open... // for now, abort and dump a core (unix systems) abort(); } We view this as a catastrophic failure and abort. Note that this mechanism functions similar to unix signals. We routinely trap things like floating point errors, segment violations, etc. See signal() for details. For more info, see p 170 (_new_handler) in the C++ Primer by Stanley B. Lippman Regards, Jeff Burch jeff@hpoemb