MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Running out of storage

What happens when the operator new cannot find a contiguous block of storage large enough to hold the desired object? A special function called the new-handler is called. Or rather, a pointer to a function is checked, and if the pointer is nonzero, then the function it points to is called.

The default behavior for the new-handler is to throw an exception , the subject covered in Chapter 16. However, if you’re using heap allocation in your program, it’s wise to at least replace the new-handler with a message that says you’ve run out of memory and then aborts the program. That way, during debugging, you’ll have a clue about what happened. For the final program you’ll want to use more robust recovery.

You replace the new-handler by including new.h and then calling set_new_handler( ) with the address of the function you want installed:

//: C13:Newhandl.cpp
// Changing the new-handler
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;

void out_of_memory() {
  cerr << "memory exhausted!" << endl;
  exit(1);
}

int main() {
  set_new_handler(out_of_memory);
  while(1)
    new int[1000]; // Exhausts memory
} ///:~ 

The new-handler function must take no arguments and have void return value. The while loop will keep allocating int objects (and throwing away their return addresses) until the free store is exhausted. At the very next call to new, no storage can be allocated, so the new-handler will be called.

Of course, you can write more sophisticated new-handlers, even one to try to reclaim memory (commonly known as a garbage collector). This is not a job for the novice programmer.

Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru