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
#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;}
   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.





Filed under C++

3 responses to “Memory Leak in Action

  1. this one is a nice example 🙂

  2. its a good observation…..Thank u Thomas

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s