Click here to Skip to main content
15,881,516 members
Articles / Programming Languages / C

C++ Memory Leak Finder

Rate me:
Please Sign up or sign in to vote.
4.96/5 (37 votes)
6 Jun 2012CPOL12 min read 149K   2.4K   124  
How to write a memory leak detection program using library injection
#include <stdio.h>
#include <execinfo.h>
#include <stdlib.h>
     
#define __USE_GNU
#include <dlfcn.h>

class allocation_info
{
private:
 
public:
};

static bool isExternalSource=true;
static void* (*real_malloc)(size_t)=0;
static void (*real_free)(void*)=0;

static void __mtrace_init(void)
{
    real_malloc = (void*(*)(size_t))dlsym(RTLD_NEXT, "malloc");
    if (real_malloc == 0) {
        fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
        return;
    }

    real_free = (void(*)(void*))dlsym(RTLD_NEXT, "free");
    if (real_free == 0) {
        fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
        return;
    }


}

extern "C" void *malloc(size_t size)
{
    if(real_malloc==0)
        __mtrace_init();

    void *p = real_malloc(size);

    if (isExternalSource)
    {
        isExternalSource = false;

        printf("Allocating %d bytes\n", size);        

        isExternalSource = true;
    }	

    return p;
}

extern "C" void free(void* ptr) 
{
    if(real_free==0)
        __mtrace_init();

    int address = (int)ptr;
    real_free(ptr);

    if (isExternalSource)
    {
        isExternalSource = false;
        printf("Freed memory at %d \n", address);        
        isExternalSource = true;
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sweden Sweden
Article videos
Oakmead Apps Android Games

21 Feb 2014: Best VB.NET Article of January 2014 - Second Prize
18 Oct 2013: Best VB.NET article of September 2013
23 Jun 2012: Best C++ article of May 2012
20 Apr 2012: Best VB.NET article of March 2012
22 Feb 2010: Best overall article of January 2010
22 Feb 2010: Best C# article of January 2010

Comments and Discussions