#ifndef __memleak_h
#define __memleak_h
/*
Provides wrappers around stdlib memory allocation to keep track of blocks
and which part of the program they were allocated from.
Any left-over blocks at exit are listed.
System is self-initialising ("lazy").

I used standard names from <stdlib.h> for the macros to enable this to be
grafted on to exisiting source. If you need to call the "raw" forms of the
functions remember to bracket the function name eg

ptr = (malloc)(size)
...
(free)(ptr)

If starting a project from scratch I recommend using your own names instead.
*/

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

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
typedef char *memleak_t;
#else
typedef void *memleak_t;
#endif

memleak_t memleak_realloc(void *, size_t, const char *, int, int);
void memleak_free(void *, const char *, int);

void memleak_set_stream(FILE *);
/* Default is stderr */

void memleak_verbose(int);
/* TRUE means log all activity, default is only list leftovers at exit */

#ifdef __cplusplus
}
#endif

#ifndef NDEBUG

#define malloc(s) memleak_realloc(0, (s), __FILE__, __LINE__,0)
#define calloc(n, s) memleak_realloc(0, (n) * (s), __FILE__, __LINE__,1)
#define realloc(p, s) memleak_realloc((p), (s), __FILE__, __LINE__,0)
#define free(p) memleak_free((p), __FILE__, __LINE__)

#else

#define memleak_set_stream(f)
#define memleak_verbose(v)

#endif

#endif
