Avoiding New Operator Failure

Author: | Posted in Programming No comments

In any programming language, arrays are the most popular and practical way for storing data, however, when allocating memory to be dedicated to an array in a C++ code, you must decide the number of elements in it when defining the array, without postponing this step to runtime.

One might think of a code such as:

cout int A

However, such code is not acceptable by the compiler as it demands a constant (static) memory allocation that can’t be changed in course of program execution…

This problem can be solved thanks to the “new” operator , as in most programs the size of the array is not decided at the compile time, we use the “new” to capture a whole memory block and dedicate it to the array , such style is called “dynamic memory allocation” …

Now we can write the following code:

cout int* array_A ;
array_A = new int

In many occasions, the new operator fails to allocate memory for many reasons that are beyond the scope of this article, we will discuss 3 methods for avoiding this problem, and process new failures.

First method: The classical method!!

A classical method is to check whether the pointer is equal to zero after dynamic allocation , the pointer is equal to zero if the new operator fails to allocate memory this can be checked by a very simple if statement after using the new operator.

Second method: Handling the exception!

Using exception handling statements, we can write a try – catch statement that catches an exception called bad_alloc defined in the library this can be illustrated by this code:

Using std::bad_alloc

Void main (void)
Double *pointer [100];
for (int i = 0; i lt; 100; i++)
Pointer[i] = new double [1000000];