Click here to Skip to main content
15,895,142 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 150.3K   2.4K   124  
How to write a memory leak detection program using library injection
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

void foo(int size)
{
    int* data = malloc(sizeof(int) * size);

    // Uncomment this to stop leak    
    //free(data);
}

void bar(int size)
{
    char *data = malloc(sizeof(char) * size);
    foo(size);

    // Uncomment this to stop leak
    //free(data);
}

void foobar(int size)
{
    bar(size);
}

void* thread_run(void* ptr)
{
    char* message = (char*)ptr;
    printf("Caller %s with id %ld\n", message, pthread_self());

    foobar(32);    
}

int main(void)
{
    printf("leakfinder C thread example app\n");
    printf("This application is expected to leak on multiple threads\n");
    
    pthread_t thread1, thread2;
    char *message1 = "Thread 1";
    char *message2 = "Thread 2";
   
    pthread_create(&thread1, NULL, thread_run, (void*)message1);
    pthread_create(&thread2, NULL, thread_run, (void*)message2);
    
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
 
    printf("leakfinder C thread example app all done\n");
    return 0;
}

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