0

if a lot of memory is dynamically allocated using new, a program can crash because newreturns 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?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
weeska
  • 439
  • 3
  • 7
  • If the third party library was compiled with exceptions, and you're compiling without exceptions, you're not going to be able to link those properly. – Mooing Duck Aug 20 '13 at 22:44
  • @MooingDuck: Interesting, do you have some resource explaining why it won't work? – weeska Aug 20 '13 at 22:54
  • 2
    @weeska: If an exception is thrown across the DLL boundary and the other side is compiled without exceptions, that side obviously won't be able to catch it. Since that side also assumes that there will be no exceptions, it will not be able to properly unwind, causing undefined behavior, usually a crash. There's no way to prevent the other side from throwing exceptions across the boundary, though you could create an exception-replacing intermediary layer. – Mooing Duck Aug 20 '13 at 22:59
  • The simple version I always use is this: think of linking as explaining a game over the phone -- you have to be very, very specific. If I say "football" and one of us shows up in pads and helmet, and the other one with nothing but kicks and a soccer ball, things are NOT going to work out well. – Stu Aug 21 '13 at 00:03

1 Answers1

1

If they throw an exception, you go here:

Global exception handling in C++

if they don't, you're hosed.

There's a reason for this, too. Think about it. How would you know where the allocations in this library are? What would you do with failures? That last one is especially important. What would you do, other than crash?

Community
  • 1
  • 1
Stu
  • 15,675
  • 4
  • 43
  • 74
  • Bad fact, nicely worded answer :D That's what I thought of, too, but you never know. Just wanted to know my options. – weeska Aug 20 '13 at 22:41