Dynamic Memory Allocation in C++

Dynamic Memory Allocation in C++

In the C++ programming language, new() is a language construct that dynamically allocates memory from free store and initialises the memory using the constructor. new() attempts to allocate enough memory in free store for the new data. If successful, it initialises the memory and returns the address to the newly allocated and initialised memory. However if new cannot allocate memory in free store it will throw an exception of type std::bad_alloc. This removes the need to explicitly check the result of an allocation. A call to delete, which calls the destructor and returns the memory allocated by new back to free store, must be made for every call to new to avoid a memory leak.

A memory leak, in computer science, occurs when a computer program consumes memory but is unable to release it back to the operating system. A memory leak has symptoms similar to a number of other problems and generally can only be diagnosed by the developer with access to the program source code.

You can use the new() operator to allocate dynamic memory. In our example we will use array.

int arraySize = 20;
double *anArray = new double[arraySize];

Allocate more space using the new() operator

 anArray = new double[2*arraySize];

The memory must be  deallocated using delete operator

 

delete [] anArray;

anArray = NULL;

Example usage of Dynamic Allocation of Arrays


#include <cstdlib>
#include <iostream>
using namespace std;

int main() {

//global variables
int array_size = 5;

//declare array
int *array = new int[array_size];

//initial array
for (int i=0; i< array_size; ++i)
 array[i] = 0;

//insert values
array[0]=13;
array[1]=45;

//print array
cout<< "array contains: ";
for (int i=0; i<array_size; ++i)
 cout<< " "<< array[i];
 cout<<endl;

//declare bigger array
cout<< "declare twice bigger array "<<endl;
int *new_array = new int[2*array_size];

//initial array
for (int i=0; i< array_size; ++i)
 new_array[i] = 0;

//copy array
cout<< "copy values from smaller to bigger array "<<endl;
for(int index=0; index<array_size; index++)
 new_array[index]=array[index];

//print array
cout<< "larger array contains: ";
for (int i=0; i<2*array_size; ++i)
 cout<< " "<< new_array[i];
 cout<<endl;

//free memory
delete [] array;
array=NULL;

//free memory
delete [] new_array;
new_array=NULL;

return 0;
}//end of main

Program Output


array contains: 13 45 0 0 0
declare twice bigger array
copy values from smaller to bigger array
larger array contains: 13 45 0 0 0 0 0 0 0 0

 

You must be logged in to post a comment.

Proudly powered by WordPress   Premium Style Theme by www.gopiplus.com
%d bloggers like this: