Last updated on June 13th, 2020 at 08:47 pm
Well, first of all we should be known with Variable Scope, Garbage Collection.
Ok, now. When we declare a variable like as follows,
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,
cout<<“Enter the number of elements: “;
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?
The above statement will do the job.