Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to avoid Memory Leaks in C/C++

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.

like image 452
Ankur Avatar asked Jun 06 '10 05:06

Ankur


2 Answers

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.

like image 153
fmark Avatar answered Oct 22 '22 17:10

fmark


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.

like image 29
Secure Avatar answered Oct 22 '22 15:10

Secure