Usage - nomius/dmemory GitHub Wiki

Introduction

Normally unexperienced C programmers tend to produce memory leaks and data corruption. This library aims to allows those programmers to create a file report informing about memory leaks, incorrect free() calls and memory corruption.

Dmemory generates a file with all the information needed to fix the bug, including the type of bug, the file and line where the memory was requested/reallocated/freed/etc and the memory address that holds that space.

Details

Compile the library

For now, dmemory supports Linux (with gcc) and HP-UX with aCC. Of course, you can use any system that includes a portable version of make and one of the compilers already supported. More compilers and systems will be supported in the future (patches with new Makefiles for other platforms are welcome).

make -f Makefile.linux

That will generate libdmemory.so (libdmemory.sl in HP-UX) that you can install everywhere you want (or leave it where it is).

Using the library

This library wraps the standard dynamic memory functions (malloc, calloc, realloc and free), so in order to use this library, you need to include the header dmemory.h in your program:

#include <dmemory.h>

Once that, your program will start using the dmemory library. In order to actually get some information, you need to put a call to the functions dmemory_init() and dmemory_end() as delimiter of the code space that you want to debug. For example, if our program example.c was:

#include <stdio.h>
#include <stdlib.h>

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

    ptr = malloc(sizeof(char)*10);
    sprintf(ptr, "Too large junk");

    return 0;
}

it will become like this:

#include <stdio.h>
#include <stdlib.h>
#include <dmemory.h>

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

    dmemory_init(0);

    ptr = malloc(sizeof(char)*10);
    sprintf(ptr, "Too large data");

    if (dmemory_end())
        return 1;

    return 0;
}

We now need to compile and run our program:

$ export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${PWD}/../dmemory
$ gcc example.c -o example -I../dmemory -L../dmemory -ldmemory
$ ./example

In this case no report and issue will be generated. In order to get a report we must tell in which file we want to save that report, you do that by using the environment variable DMEMORY_REPORT. Let's see how that works:

$ export DMEMORY_REPORT=report.txt
$ ./example

Now we have our report generated, let's see how it looks like:

$ cat report.txt
(L) [example.c] [11] (address: 0x000008fe1030)
(C) [example.c] [11] (address: 0x000008fe1030)
$

The report tells us that there was a memory leak in the file example.c at line 11, which is our call to the malloc line, and a memory corruption in the same address space. This corruption was produced because we tried to put a big chunk of data in a small memory space (in our sprintf call).

⚠️ **GitHub.com Fallback** ⚠️