Memory leaks or corruption in programs occur mainly due to following reasons:
1. Inadequate knowledge about Memory Management:
This is true for most people when they start programming. With experience they learn how memory management works in general and overtime they become “responsible” developers who understand how precious memory is.
2. Inadequate knowledge of specific System APIs or tools
A Programmer starting to work with a new language or platform might not be aware of how stuff works inside that system. e.g. A newbie Windows programmer may not know that CreateCompatibleDC() call must have a corresponding DeleteDC() call and GetDC() call must have a corresponding ReleaseDC() call. Again experience helps here.
3. Unreviewed Code
Not spending enough time in reviewing code. We are always in a hurry and don’t bother to implement code to handle exceptions. Doing Self or Peer code review can eliminate most of these traps. Note that its very costly (in time and money) when problems surface later in the field. It easy to fix bugs when they are caught on the development machine.
4. Using Free Code
So much code is available on the web these days that software development has now become some sort of software integration activity. Well… reusing code is not bad, but not knowing how it works is. Quality of free code must be questioned at all times. Sample code is not always ready to be used for production purposes.
5. Not using memory detection tools
Your program might leak memory even if you take care of above five conditions. Its a good habit to use tools that can help in detecting memory leaks which would otherwise go undetected.
My next post will be about Application Verifier tool which is a great tool for detecting memory leaks in native embedded applications for Windows CE and Windows Mobile.