if a lot of memory is dynamically allocated using new
, a program can crash because new
returns NULL
. Using exceptions, one can catch std::bad_alloc and do what fits best:
try{
allocate_much_memory();
catch( std::exception e){
do_something_that_fits();
}
If one can't use exceptions for whatever reason, one needs to check for NULL
:
BigBlob* allocate_much_memory(){
BigBlob *bblob = new BigBlob();
if( bblob == NULL ){
std::cerr << "uh-oh" << std::endl;
handle_error();
}
return bblob;
}
The point is, as far as i understand, you have to write the check for NULL on your own. What can you do, if you can't change the function because it's from a third party library, and you don't use exceptions?
Update: For the part where i'm checking if the result of new BigBlob()
is NULL
: That isn't necessary: see Do I need to check for NULL after p = new Fred()? and How can I convince my (older) compiler to automatically check new to see if it returns NULL?