1

In the code

std::vector<int> vec(length);
vec.resize(2*length);
vec.push_back(4);
vec.reserve(3*length);

all statements might throw a bad_alloc exception, if the allocation a n-times length integers fails (see reserve and resize).

I see two approaches to handle this exception

  • Use a try catch clause at all occurrences of a possible vector memory allocation to catch the exception.
  • Overload new and add exception handling there for all occurrences.

I maintain a large code base, thus the first option seams rather cumbersome and will also spoil the readability of the code.

What is the best best practise to check if a memory allocation of a std::vector worked?

schorsch312
  • 5,553
  • 5
  • 28
  • 57
  • 3
    You're asking the wrong question. You should really ask _what to do when I can't allocate the memory I need_ and _Can I recover from this situation and how/where_. If you've answered them, you know where to place the try-catch. – tkausl Nov 12 '18 at 13:48
  • 3
    In both of the proposed approaches, there's an important detail left dangling: what would the code do if memory allocation failed? That's the first question you have to answer; the rest is just implementation details. – Pete Becker Nov 12 '18 at 14:00
  • 1
    If an exception is not thrown, the memory allocation succeeded. Rather than using a `try`/`catch` block around every operation, centralise it - for example, have a single block in `main()` that catches all exceptions thrown by called functions. Develop those functions so, if an exception is thrown, the functions leave the program in a sane state. That way, if an exception is caught by `main()`, the exception handler can either recover and retry or - if that isn't possible - simply terminate the program. – Peter Nov 12 '18 at 14:02

1 Answers1

2

Catch std::bad_alloc at the program or module level, at a point where you can properly handle it by terminating the program or canceling what the module did.

At the program level: Add a try catch in your main, display a message then exit.

At the module level: Add a try catch around the entry point DoStuffWhichRequiresALotOfMemory() of your module. Make sure that after std::bad_alloc is thrown your program is still in a valid state, f.i. the module has a separate state to the rest of the program or it's functional without side effects. Display a message and you are done.

Handling memory allocation failure at such a low level is impractical. If you need these guarantees, allocate all the memory beforehand (for the whole module, not only for your vector) and use an allocator. Then you only have one point where it can fail.

I know this does not directly answer the question, but I urge you to think about your problem again.