Allocating and Deallocating memory OR use of New/Delete OR allocating memory in runtime OR declaring array in runtime | in C++

Well, first of all we should be known with Variable Scope, Garbage Collection.

Ok, now. When we declare a variable like as follows,

int a;

it allocates a specific portion of memory for that variable and when we go beyond the scope of the variable the garbage collection system automatically deallocates or in general, deletes the memory location which was occupied by the variable.

But in some cases, like when declaring an array, we might need to allocate a number of array elements which we don’t and which will be specified by the user at the runtime. In such a case we have to declare the array with the number of elements given by the user. Here, we can use the new operator as follows,

int *a = new int[x];

Here, the value of x defined the number of elements in the array a and the value of x is given by the user. Like as follows,

int x;
cout<<"Enter the number of elements: ";
int *a = new int[x];

So you see, we have taken the number of elements of our array from the user and then we declare the array with the new operator.

Variable declared with new operator does not die even the execution of the program goes beyond the scope of the variable. So in the runtime when we don’t need a variable anymore, the variable still stay alive eating some memory which can also lead us to memory leak.

So how can we delete the memory we allocated using new operator while we don’t need the memory anymore?

delete a;

The above statement will do the job.

Author: Tanmay Chakrabarty

Tanmay Chakrabarty is a former CSE student, currently working as a Senior Software Engineer with 5+ years of experience in the field of Web Application development in PHP+MySQL platform with strong skills in Javascript, JQuery, JQuery UI and CSS. He tries to write notes every week but fails due to heavy loads of duty.

Recommended Recommends


Contact Us