What is memory leak? If your program reserve memory at run time and do not unallocate the memory after the program end - such a program is said to have a memory leak.
If you repeatedly run the program (which allocates memory but does not unallocate it), then more and more of your computers free memory will be reserved. Eventually, your computer will run out of free memory, an the program will not be able to run at all.
The more memory reserved and not unallocated, the faster your computer's free memory will be reduced. Dynamic arrays in C++ can allocate massive amounts of memory, so it is crucial that the memory allocated for these is deallocated when they are no longer needed.
If your program has a memory leak (it allocates memory but does not unallocate it before existing), then the only way to reclaim the memory back is to reboot your computer.
Memory leaks are the sign of sloppy and careless work. Always ensure your programs have no memory leaks.
Following is C++ program which allocate dynamic array and deallocate at the end of program.
| Code: |
#include<iostream>
using std::cout;
using std::endl;
using std::cin;
using std::cerr;
int main(void)
{
int numEntries = 0; /* size of dynamic array */
int *iPtr; /* pointer to dynamic array */
int count = 0;
cout<< "How many values do your require ==> ";
cin>> numEntries;
iPtr = new int[numEntries]; /* allocate memory for entire
array */
if (iPtr == NULL) /* was the memory allocated successfully */
{
cerr<< "Out of Memory!\n";
return 1;
}
for (count = 0; count < numEntries; count++)
{
cout<< "\nEnter value [" << (count + 1) << "] : ";
cin>> iPtr[count];
}
cout<< "\nYou Entered these values :" << endl;
for (count = 0; count < numEntries; count++)
{
/* display array elements */
cout<< "\nValue [" << (count + 1) << "] = " <<
iPtr[count];
}
delete [] iPtr; /* reclaim all memory
reserved for the array */
iPtr = NULL; /* set pointer to NULL */
return 0;
}
|
Here in the program :
In order to allocate memory
| Code: |
iPtr = new int[numEntries]; /* allocate memory for the entire array */
|
In order to free the memory
| Code: |
delete [] iPtr; /* reclaim all memory reserved for the array */
iPtr = NULL; /* set pointer to NULL */
|
I hope Mr. Tousif will be able to pour few more deep explanation.
-DK.
_________________
...we too are stardust...