![]() |
VOOZH | about |
In this article, if memory allocation using new is failed in C++ then how it should be handled? When an object of a class is created dynamically using new operator, the object occupies memory in the heap. Below are the major thing that must be keep in mind:
Below is the program that occupies a large amount of memory so that the problem will occur. Use memory allocation statements in the try and catch block and for preventing memory crash and throw the exception when memory allocation is failed.
Program 1:
Memory Allocation is failed: std::bad_alloc
The above memory failure issue can be resolved without using the try-catch block. It can be fixed by using nothrow version of the new operator:
Below is the implementation of memory allocation using nothrow operator:
Program 2:
Memory allocation fails