News for hackers. Stuff that matters.
Re:Tips and Tricks to avoid memory leaks in writing C by lea on Saturday June 25, 2011 @11:10AM (#2695788)
a simple and efficient method for finding memory leaks is replacing malloc/free with house-keeping macros when debugging:

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

  void *(*_malloc_old) (size_t size) = malloc;
  void (*_free_old) (void *ptr) = free;

  #define malloc(size) _malloc_new (size, __FUNCTION__, __LINE__)
  #define free(ptr) _free_new (ptr)

  struct alloc
  {
        const char *function;
        int line;
        void *ptr;
        struct alloc *next;
  };
  struct alloc *list = NULL;

  void *_malloc_new (size_t size, const char *function, int line)
  {
        struct alloc *e = _malloc_old (sizeof *e);
        void *ptr = _malloc_old (size);

        e->function = function;
        e->line = line;
        e->ptr = ptr;

        e->next = list;
        list = e;

        return (ptr);
  }
  void *_free_new (void *ptr)
  {
        struct alloc *prev = NULL, *e = list;
        while (e) {
                if (e->ptr == ptr) {
                        break;
                }
                prev = e;
                e = e->next;
        }
        if (e) {
                if (e == list) {
                        list = NULL;
                }
                if (prev) {
                        prev->next = e->next;
                }
                _free_old (e);
        }
        _free_old (ptr);
  }
  void pallocs (FILE *f)
  {
        struct alloc *e = list;
        while (e) {
                fprintf (f, "%s:%d\t0x%x\n", e->function, e->line, (size_t)e->ptr);
                e = e->next;
        }

  }
  int main ()
  {
        void *ptr = malloc (1024);
        void *leak = malloc (1024);
        void *leak2 = malloc (1024);

        printf ("before free:\n");
        pallocs (stdout);

        printf ("after free:\n");
        free (ptr);

        pallocs (stdout);
  }
outputs:

  before free:
  main:67 0x9dab860
  main:66 0x9dab440
  main:65 0x9dab020
  after free:
  main:67 0x9dab860
  main:66 0x9dab440

There are no comments on this comment yet.