1 2 3 4 5 6 7 8 9 10 11 12

[16.5] Do I need to check for NULL after p = new Fred()?

No!

If your compiler doesn't support (or if you refuse to use) exceptions, your code might be even more tedious:

Fred* p = new Fred();
if (p == NULL) {
cerr << "Couldn't allocate memory for a Fred" << endl;
abort();
}

In C++, if the runtime system cannot allocate sizeof(Fred) bytes of memory during p = new Fred(), a bad_alloc exception will be thrown. Unlike malloc(), new never returns NULL!

Therefore you should simply write:

Fred* p = new Fred();

// No need to check if p is NULL

24-Mar-98

Page 9

TAM/C201