2011-04-16, 03:10 PM
Any general tips for reducing memory leaks when you're putting together a basic computer program?
2011-04-18, 02:37 PM
A memory leak occurs when memory is allocated (for example using a malloc() function), and not released. Often the error is caused by allocating the memory then returning from a function before de-allocating it.
To avoid the problem requres two steps:
Obviously, be careful writing code so that whenever memory is allocated, its always deallocated properly.
Add code so that the amount of free memory is visible; that way you can detect memory leaks - although not necessarily who's doing it.
As a part of the second step, it may be useful to have your own versions of malloc(), realloc() and free() which keep track of which functions call them. That can make it easier to find out who "owns" the lost memory.
One nasty problem is the operating system leaking memory. This is much harder to detect, apart from the application gradually slowing down as the dynamic memory has to start using hard drive as memory.
Read more: Answers.com - What is a memory leak and how can you avoid it (http://wiki.answers.com/Q/What_is_a_memory_leak_and_how_can_you_avoid_it)