What if memory allocation using new fails in C++ how to handle

(Last Updated On: December 20, 2017)

Interview Question on memory allocation failure in C++: when you do memory allocation using new in C++ and it fails then what are issues? In another words, when you allocate memory on heap using new operator, how do you handle memory allocation using new in C++ failure? What is issue when you don’t handle it?

The answer for this technical interview question i.e. if C++ new fails to allocate memory will include 2 techniques to handle dynamic memory allocation using new failure in C++.

Answer: When we allocate memory from heap dynamically in a C++ program using new operator, program crashes when memory is not available or system is not able to allocate memory to a program, as it throws an exception. So, to prevent program crash, we need to handle the exception when memory allocation fails.

 

Techniques to handle bad allocation exception in C++ program:

 

Using Try Catch Block with std::bad_alloc exception

We need to put the memory allocation code using new operator in try catch block. Below C++ program catches exception when it is thrown on memory allocation failure.

 

 

Using no_throw version of “new” i.e. new(std::nothrow)

Rather than simply using new operator for memory allocation in C++, we need to use no throw version of “new” as it handle the exception and there is no program crash.