C++ Gotchas: Avoiding Common Problems in Coding and Design

Category: Programming
Author: Stephen C. Dewhurst
This Month Stack Overflow 1


by John Feminella   2019-01-13

In general, don't check for memory allocation failures on small allocations. Inevitably, it's more trouble than it's worth, and it's hard to get right anyway. And most of the time there's nothing you can do about it. On very large memory operations, if you can do something about it, it might be worth considering things on a case-by-case basis.

This is well covered by C++ Gotchas: Avoiding Common Problems in Coding and Design. In particular, see 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.

[...] 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.