Exceptions - nomius/dmemory GitHub Wiki

Introduction

It's common that you have malloc calls all over your program and some of those never get freed because you need them in all the excecution of your program. That's not actually a good practice, but dmemory support all your dirty code.

Also, is quite common that you're working on code that you didn't write, and you can't assume every line other people wrote to be 100% correct.

In both of those cases you need somehow to tell dmemory "hey, ignore the leaks in there".

Those are called exceptions, and it's a way to tell dmemory to ignore some bugs in your code. Of course, exceptions are valid for memory leaks, not for memory corruptions, we assume that those last ones must always get fixed.

NOTE: _What should we do with double memory free? As strdup will not be added to the stack, but free in this case will be correct... Maybe an EXCEPTIONS__DOUBLE_FREE file?

Details

Exceptions are created in a file, all you need to do is to create a file with the filename and the line separated by a pipe character (|). If you want to ignore a whole filename, you can put just the filename in the exceptions file and all memory leaks in it will be ignored. Every exception goes in a new line.

Let's see an example of a program with memory leaks:

$ cat bug1.c
#include <stdio.h>
#include <stdlib.h>
#include <dmemory.h>

int main(int argc, char *argv[])
{
    int *ptr1, *ptr2;

    dmemory_init(0);

    ptr1 = malloc(sizeof(int) * 5);
    ptr2 = malloc(sizeof(int) * 5);
    myfunc();

    if (dmemory_end())
        return 1;

    return 0;
}
$ cat bug2.c
#include <stdlib.h>
#include <dmemory.h>

void myfunc(void)
{
    char *ptr;

    ptr = malloc(sizeof(char) * 5);
}
$

First let's compile our program:

$ gcc bug1.c -c -o bug1.o -I../dmemory
$ gcc bug2.c -c -o bug2.o -I../dmemory
$ gcc bug1.o bug2.o -o bugs -L../dmemory -ldmemory

Now, let's create an exception file:

$ cat exceptions.txt
bug1.c|11
bug2.c
$

That excetions.txt file will tell dmemory to ignore the memory leak produced in line 11 on file bug1.c and all memory leaks in bug2.c.

Now, all we have to do is to tell dmemory to use that exceptions file. The way to do that is with the environment variable DMEMORY_EXCEPTIONS. Let's see how it works:

$ export DMEMORY_REPORT=report.txt
$ export DMEMORY_EXCEPTIONS=exceptions.txt
$ ./bugs

Now, if we see the report generated we'll see only the leak generated in line 12, while memory leaks generated in bug1.c at line 11 and bug2.c are ignored:

$ cat report.txt 
(L) [bug1.c] [12] (address: 0x00000839d088)
$
⚠️ **GitHub.com Fallback** ⚠️