Handling Out Of Memory Errors in Code
In this article we will learn, how we can handle out of memory errors in a C++ application.
- Handling out of memory crashes by catching exceptions
- Calling a special function if out of memory happens.
As we know each process has only a limited free storage or heap which can be associated with dynamic memory allocation. If application allocates or consumes all the memory then our process will crash with out of memory error.
We can make similar scenario by allocating memory in heap with loop continuously without deleting that memory. Due to limited free storage after consuming memory to a certain point program will crash.
e.g.
#include<iostream> int main() { // Keep allocating memory continuously till heap become full // new throws exception and application is crashed while(true) { int * num = new int[1000]; } return 0; }
If we run this program in 32 Bit Application process where maximum size is 2^32 which will take lesser time to crash than a 64 Bit Application whose limit is 2^64 which may take whole lot of time to crash.
To handle this we can build our own 32 Bit version from a 64 Bit OS by adding g++ -m32 main.cpp in the program. Then the above program will crash as memory from heap is consumed and new or new[] fails to allocate memory then new throws an exception std::badalloc
, and if a application doesn’t catch this exception it will crash.
Handling out of memory crashes by catching exceptions :
We can also catch the std::badalloc
exeption.
#include<iostream> #include<new> int main() { try { // Keep allocating memory continuously till heap become full // new throws exception and application is crashed while(true) { int * num = new int[1000]; } } catch (std::bad_alloc& excObj) { std::cout << "bad_alloc Exception :: Out Of Memory or Unable to allocate memory " << excObj.what() << '\n'; } return 0; }
Calling a special function if out of memory happens :
In case new or new[] are unable to allocate memory, a special function i.e. new_handler is called. new_handler would return if it successfully made available some new memory. Else it should exit the application or it will enter into never ending cycle.
In his special function we can do anything like,
- By deleting memory from heap, we can make available some memory.
- Starting another instance of application as a separate process, so that it can continue its service, etc.
#include <iostream> #include <cstdlib> #include <new> void outOfMemory_orUnableAllocating() { std::cout<<"Out of Memory :: Handler \n"; // If unable to make memory available, exit else return. std::exit (1); } int main() { // Seting new handler std::set_new_handler(outOfMemory_orUnableAllocating); // Keep allocating memory continuously till heap become full // new throws exception and application is crashed while(true) { int * num = new int[1000]; } return 0; }