1 // stb_leakcheck.h - v0.3 - quick & dirty malloc leak-checking - public domain
4 // This software is dual-licensed to the public domain and under the following
5 // license: you are granted a perpetual, irrevocable license to copy, modify,
6 // publish, and distribute this file as you see fit.
8 #ifdef STB_LEAKCHECK_IMPLEMENTATION
9 #undef STB_LEAKCHECK_IMPLEMENTATION // don't implement more than once
11 // if we've already included leakcheck before, undefine the macros
23 typedef struct malloc_info stb_leakcheck_malloc_info
;
30 stb_leakcheck_malloc_info
*next
,*prev
;
33 static stb_leakcheck_malloc_info
*mi_head
;
35 void *stb_leakcheck_malloc(size_t sz
, char *file
, int line
)
37 stb_leakcheck_malloc_info
*mi
= (stb_leakcheck_malloc_info
*) malloc(sz
+ sizeof(*mi
));
38 if (mi
== NULL
) return mi
;
50 void stb_leakcheck_free(void *ptr
)
53 stb_leakcheck_malloc_info
*mi
= (stb_leakcheck_malloc_info
*) ptr
- 1;
55 #ifndef STB_LEAKCHECK_SHOWALL
56 if (mi
->prev
== NULL
) {
57 assert(mi_head
== mi
);
60 mi
->prev
->next
= mi
->next
;
62 mi
->next
->prev
= mi
->prev
;
67 void *stb_leakcheck_realloc(void *ptr
, size_t sz
, char *file
, int line
)
70 return stb_leakcheck_malloc(sz
, file
, line
);
72 stb_leakcheck_free(ptr
);
75 stb_leakcheck_malloc_info
*mi
= (stb_leakcheck_malloc_info
*) ptr
- 1;
79 #ifdef STB_LEAKCHECK_REALLOC_PRESERVE_MALLOC_FILELINE
80 void *q
= stb_leakcheck_malloc(sz
, mi
->file
, mi
->line
);
82 void *q
= stb_leakcheck_malloc(sz
, file
, line
);
85 memcpy(q
, ptr
, mi
->size
);
86 stb_leakcheck_free(ptr
);
93 void stb_leakcheck_dumpmem(void)
95 stb_leakcheck_malloc_info
*mi
= mi_head
;
97 if ((ptrdiff_t) mi
->size
>= 0)
98 printf("LEAKED: %s (%4d): %8d bytes at %p\n", mi
->file
, mi
->line
, (int) mi
->size
, mi
+1);
101 #ifdef STB_LEAKCHECK_SHOWALL
104 if ((ptrdiff_t) mi
->size
< 0)
105 printf("FREED : %s (%4d): %8d bytes at %p\n", mi
->file
, mi
->line
, (int) ~mi
->size
, mi
+1);
110 #endif // STB_LEAKCHECK_IMPLEMENTATION
112 #ifndef INCLUDE_STB_LEAKCHECK_H
113 #define INCLUDE_STB_LEAKCHECK_H
115 #define malloc(sz) stb_leakcheck_malloc(sz, __FILE__, __LINE__)
116 #define free(p) stb_leakcheck_free(p)
117 #define realloc(p,sz) stb_leakcheck_realloc(p,sz, __FILE__, __LINE__)
119 extern void * stb_leakcheck_malloc(size_t sz
, char *file
, int line
);
120 extern void * stb_leakcheck_realloc(void *ptr
, size_t sz
, char *file
, int line
);
121 extern void stb_leakcheck_free(void *ptr
);
122 extern void stb_leakcheck_dumpmem(void);
124 #endif // INCLUDE_STB_LEAKCHECK_H