Tag Archives: pointers

Memory Leak in Action

The most important and interesting thing we come across while learning about pointers is memory leak. If we declare a pointer and forgets to delete it manually, it will stay in existence and can cause memory leak. I do not know how many of you have tried to see it in action. However I wanted to see it and so I wrote this small code:

//The program illustrates the destructive power of pointers
//Author:Thomas Mathew tm1729@gmail.com
#include "iostream"
using namespace std;

int main()
{
   int i=0;
   while (i!=-1){
         double *pi = new double;
         if (i%100000==0) { cout<<"Pointer : "<<i<<" Address: "<<pi<<endl;}
         i++;
         }
   return 0;
}

To see the effect of the code on memory consumption, have a look at the system monitor display

As you can see the memory consumption increases so rapidly and once it uses 100% RAM, it starts to use up Swap. And as soon as I terminate the program, its all back to normal. The ripple effect is due to the occasional cout command. You can change the frequency of cout and see how fast/slow memory consumption increases.

 

 

3 Comments

Filed under C++