The Mtlib Memory Tracking Library

by Marco Tabini



Example 1:



char *test(int a)

{

    char *tmp;

    tmp = malloc (3);

    if (a > 99)

        return FALSE;

    sprintf (tmp, "%d", a);

    return tmp;

}

char *useme()

{

    int i;

    char *str;

    for (i = 0; i <= 100; i++)

    {



       str = test (i);

        if (str)

        {

            printf (str);

            free (str);

        }

    }

}



Example 2:



#define malloc mt_malloc

#define calloc mt_calloc

#define realloc mt_realloc

#define free mt_free





Figure 1:



This is a test

This is another test



WARNING!!!



Possible memory leaks detected:

===============================

ID: 0, size 100 bytes







Figure 2:



This is a test

This is another test



WARNING!!!



Possible memory leaks detected:

===============================

ID: 0, size 100 bytes, allocated in test.c:8





Listing One

// These definitions overwrite the stlib functions. stdlib should

// still be included before this file.



#define malloc mt_malloc

#define calloc mt_calloc

#define realloc mt_realloc

#define free mt_free



void *mt_malloc (size_t size);

void *mt_calloc (size_t items, size_t size);

void *mt_realloc (void *ptr, size_t size);

void *mt_free (void *ptr);

void mt_terminate();





Listing Two



#include <stdlib.h>

#include "../mtlib.h"



int main (void)

{

    char *a;

    a = malloc (100);

    sprintf (a, "This is a test\n");

    printf (a);

    // The memory leak occurs here

    a = malloc (100);

    sprintf (a, "This is another test\n");

    printf (a);

    free (a);

    mt_terminate();

    return 0;

}





Listing Three



// These definitions overwrite the stlib functions. Note that stdlib should

// still be included before this file.



#define malloc(size) mt_malloc(size,__FILE__,__LINE__)

#define calloc(items,size) mt_calloc(items,size,__FILE__,__LINE__)

#define realloc(ptr,size) mt_realloc(ptr,size,__FILE__,__LINE__)

#define free mt_free



void *mt_malloc (size_t size, char *filename, long line);

void *mt_calloc (size_t items, size_t size, char *filename, long line);

void *mt_realloc (void *ptr, size_t size, char *filename, long line);

void *mt_free (void *ptr);



void mt_terminate();





Listing Four



#include <stdlib.h>

#define DEBUG

#include "../mtfree.h"

// This function is where the memory leak occurs

void testme(MT_CONTEXT_DATA)

{

    char *t = MT_MALLOC (10);

    strcpy (t, "Test");

    printf (t);

}

// This is the thread's main entry point

int thread_main (void)

{

    MT_DECLARE_DATA

    MT_INITIALIZE("My Thread")

    testme (MT_CALL_DATA);

    MT_TERMINATE

}

// This function calls the thread main function three times--you should adapt

// it to your platform's threading functionality

int main (void)

{

    thread_main();

    thread_main();

    thread_main();

    return 0;

}













3



