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

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,  the program crashes when memory is not available, or the 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.

#include <iostream>
using namespace std;

int main(){

	//Try to allocate very huge amount of memory
	//so memory allocation fails.
	long CHUNK_SIZE = 0x7fffffff;

	//Allocate memory dynamically using "new" 
	// using try catch block

	try {
		char *ptr = new char[CHUNK_SIZE];
		//on exception below line will not be printed.
		//and control will go in catch block.
		cout<<"Memory allocation Successful"<<endl;
	}
	catch (const bad_alloc& e) {

		cout << "Allocation failed: " << e.what() << '\n';
		//handle error
	}		

	return 0;
}

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.

#include <iostream>
using namespace std;

int main(){

	//Try to allocate very huge amount of memory
	//so memory allocation fails.
	long CHUNK_SIZE = 0x7fffffff;

	//Allocate memory dynamically using "new" with
	//"nothrow" version of new
	char *ptr = new(std::nothrow) char[CHUNK_SIZE];
	
	//Chek ptr if it contains the valild address of
	//allocated memory
	if (ptr)
	{
		cout<<"Memory allocation Successful"<<endl;
		//do operations
	}  
	else{
		cout << "Memory allocation fails" << endl;
	}      

	return 0;
}

Related Posts