C++ Dynamic Memory Allocation of Arrays

We have already discussed Dynamic Memory Allocation in C style through malloc, calloc and realloc : C++ Program to illustrate memory allocation with malloc, calloc and realloc .

The static memory allocation of array leads to inefficient use of memory. Moreover, it is statically bounded and can not be allocated on demand at runtime. Some programs require memory to be allocated based on user input. This leads to the need of dynamic memory allocation for arrays.

MEMORY ALLOCATION

In C++, Dynamic Memory Allocation takes place with the help of two operators i.e. new and delete. The general syntax for memory allocation goes as:

pointer = new datatype [ number_of_elements ] 

The above expression is used to allocate a block of elements of type datatype. The number_of_elements is an integer value which denotes the number of elements of the array. A pointer to the beginning of new memory block is returned.

For instance,

int *list;
list = new int [5];

In the above scenario, the system will dynamically allocate memory for 5 integer type elements and return a pointer to the beginning of this block to list.


Once the memory is allocated, list will behave similarly as a static array of 5 integer elements. The elements can be accessed as list[0], list[1], ... list[4].

The dynamic memory allocation takes place from the system heap memory. As we know that the system memory is limited and may exhaust, thus the request for dynamic memory allocation may fail. 

One way to identify whether memory allocation is successful or not is through the use of a special object nothrow defined in the <new> header. 


list = new (nothrow) int [5];

By using nothrow, if the memory allocation fails, a null pointer is returned to the pointer and the program continues its execution.

For instance,

int *list;
list = new (nothrow) int [5];

if( list == nullptr )
{
     // MEASURES IF ALLOCATION FAILS
}

// REST OF CODE

MEMORY DEALLOCATION

After the use of memory, the allocated memory can be freed so that is can be used for further requests of dynamic memory. For this purpose, delete operator is used whose syntax is as follows:

delete [] pointer; 

Share this

Related Posts

FIND US ON FACEBOOK!