What are some tips I can use to avoid memory leaks in my applications? In my current project I use a tool "INSURE++" which finds the memory leak and generate the report.
Apart from the tool is there any method to identify memory leaks and overcome it.
There are three main ways of doing this.
The first is to not create memory leaks in the first place. Defensive programming techniques are invaluable here. See this excellent presentation for a summary of this issues, or the relevant chapter in Secure C Coding. I am more familiar with C than C++, but I understand that C++'s smart pointers are useful here.
A second approach static analysis, which attempts to detect errors in your source-code. The original tool in this category is lint, which is now sadly outdated. The best tools, as far as I know, are commercial such as coverty. However, some free tools do exist.
The third approach is to detect memory leaks at runtime, like INSURE++ does. Valgrind is excellent here and highly recommended. It may help catch bugs you've already introduced. It is especially helpful if you do have a test suite that has good code coverage.
For C, a good code organization helps. I.e. don't throw calls to malloc() and free() all over your codebase. Centralize them into two functions, then you have one single point for all the checkings. The simplest one could be to count the successful calls and check at program exit that they are balanced.
static unsigned long mymem_count_alloc = 0;
static unsigned long mymem_count_free = 0;
void *mymem_alloc (size_t size)
{
void *p;
p = malloc(size);
if (p)
{
mymem_count_alloc++;
}
else
error logging/handling/signaling
return (p);
}
void mymem_free (void *p)
{
if (p)
{
free(p);
mymem_count_free++;
}
}
void mymem_check (void)
{
if (mymem_count_alloc != mymem_count_free)
error alert
}
You can continue this for the different data structures. Whereever you need to allocate memory for a string, use mystr_alloc and mystr_free. And so on. When a leak is detected this way, you can quickly narrow it down.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With