Wednesday, July 20, 2011

Episode_10_Memory_Leak (The scariest nightmare for a programmer)


Memory leak often occurs when a computer program is unable to release the memory back to the operating system. In programming, a memory leak happens when an object is stored in a memory but cannot be accessed by the running code and generally can only be diagnosed by a programmer with access to the program source code. However, many people refer to any unwanted increase in memory usage as a memory leak, though this is not strictly accurate from a technical perspective.

picture 0_memory_leak_OpenCv
That's an example when memory leak occured in my program, so I diagnosed my source code. It usually happens when we loop the program continuously. Well, if you make a program, you must check step by step your source code whether it is stable or not. After you run your program, you can check with task manager and search your name of the program ***.exe. It will show you how much memory is used by your program.

picture 1_check_memory_myprogram_with_task_manager

So After I have diagnosed and repaired my source code, it shows that I just used 18.064k of 2,00GB memory.

picture 2_myprogram_more_stable_after_diagnose
With your looping source code, I say again that you must be careful with your code that is unable to release memory back to the operating system. I will give an Example in OpenCv source code (C++):

Source Code here :

...
while(1){
  ...
  ...
  result = cvCreateImage(size, frame->depth, frame->nChannels); // its wrong
  tes = cvLoadImage("smile.png",1); //wrong
  cvNamedWindow("original", CV_WINDOW_AUTOSIZE); //wrong again
  cvSaveImage("Temp.jpg",img); //also wrong
  ...
  ...
  }
return0;
}

And many other events that you can find with your source code that is important to located it in your looping section.
...
...
cvNamedWindow("original", CV_WINDOW_AUTOSIZE);
result = cvCreateImage(size, frame->depth, frame->nChannels);
while(1){
  ...
  ...
  if (Load == TRUE) tes = cvLoadImage("smile.png",1);
  if (Save == TRUE) cvSaveImage("Temp.jpg",img);
  ...
  ...
  }
return0;
}

Note : It is simple but important especially it can drive you crazy when your program is finished but unstable and consuming huge amounts of memory.


0 comments:

Post a Comment