Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Gotcha #61: Checking for Allocation Failure

Some questions should just not be asked, and whether a particular memory allocation has succeeded is one of them.

Let's look at how life used to be in C++ when allocating memory. Here's some code that's careful to check that every memory allocation succeeds:

bool error = false;
String **array = new String *[n];
if( array ) {
  for( String **p = array; p < array+n; ++p ) {
    String *tmp = new String;
    if( tmp )
      *p = tmp;
    else {
      error = true;
      break;
    }
  }
}
else
  error = true;
if( error )
  handleError();

This style of coding is a lot of trouble, but it might be worth the effort if it were able to detect all possible memory allocation failures. It won't. Unfortunately, the String constructor itself may encounter a memory allocation error, and there is no easy way to propagate that error out of the constructor. It's possible, but not a pleasant prospect, to have the String constructor put the String object in some sort of acceptable error state and set a flag that can be checked by users of the class. Even assuming we have access to the implementation of String to implement this behavior, this approach gives both the original author of the code and all future maintainers yet another condition to test.

Or neglect to test. Error-checking code that's this involved is rarely entirely correct initially and is almost never correct after a period of maintenance. A better approach is not to check at all:

String **array = new String *[n];
for( String **p = array; p < array+n; ++p )
  *p = new String;

This code is shorter, clearer, faster, and correct. The standard behavior of new is to throw a bad_alloc exception in the event of allocation failure. This allows us to encapsulate error-handling code for allocation failure from the rest of the program, resulting in a cleaner, clearer, and generally more efficient design.

In any case, an attempt to check the result of a standard use of new will never indicate a failure, since the use of new will either succeed or throw an exception:

int *ip = new int;
if( ip ) { // condition always true
  // . . . 
}
else {
  // will never execute
}

It's possible to employ the standard "nothrow" version of operator new that will return a null pointer on failure:

int *ip = new (nothrow) int;
if( ip ) { // condition almost always true
  // . . . 
}
else {
  // will almost never execute
}

However, this simply brings back the problems associated with the old semantics of new, with the added detriment of hideous syntax. It's better to avoid this clumsy backward compatibility hack and simply design and code for the exception-throwing new.

The runtime system will also handle automatically a particularly nasty problem in allocation failure. Recall that the new operator actually specifies two function calls: a call to an operator new function to allocate storage, followed by an invocation of a constructor to initialize the storage:

Thing *tp = new Thing( arg );

If we catch a bad_alloc exception, we know there was a memory allocation error, but where? The error could have occurred in the original allocation of the storage for Thing, or it could have occurred within the constructor for Thing. In the first case we have no memory to deallocate, since tp was never set to anything. In the second case, we should return the (uninitialized) memory to which tp refers to the heap. However, it can be difficult or impossible to determine which is the case.

Fortunately, the runtime system handles this situation for us. If the original allocation of storage for the Thing object succeeds but the Thing constructor fails and throws any exception, the runtime system will call an appropriate operator delete (see Gotcha #62) to reclaim the storage.

  • + Share This
  • 🔖 Save To Your Account