From a932d4f46c2fadd6c750d844846fb9ba4baf45e0 Mon Sep 17 00:00:00 2001 From: Tavian Barnes Date: Mon, 16 May 2011 23:44:06 -0600 Subject: Add basic leak check. --- libdimension/malloc.c | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) (limited to 'libdimension/malloc.c') diff --git a/libdimension/malloc.c b/libdimension/malloc.c index 91364d4..2f11281 100644 --- a/libdimension/malloc.c +++ b/libdimension/malloc.c @@ -23,10 +23,14 @@ * Dynamic memory. */ -#include "dimension.h" +#include "dimension-impl.h" #include #include +#ifndef NDEBUG +static size_t dmnsn_allocs = 0; +#endif + void * dmnsn_malloc(size_t size) { @@ -34,12 +38,23 @@ dmnsn_malloc(size_t size) if (!ptr) { dmnsn_error("Memory allocation failed."); } + +#ifndef NDEBUG + __sync_fetch_and_add(&dmnsn_allocs, 1); +#endif + return ptr; } void * dmnsn_realloc(void *ptr, size_t size) { +#ifndef NDEBUG + if (!ptr) { + __sync_fetch_and_add(&dmnsn_allocs, 1); + } +#endif + ptr = realloc(ptr, size); if (!ptr) { dmnsn_error("Memory allocation failed."); @@ -58,5 +73,21 @@ dmnsn_strdup(const char *s) void dmnsn_free(void *ptr) { +#ifndef NDEBUG + if (ptr) { + __sync_fetch_and_sub(&dmnsn_allocs, 1); + } +#endif + free(ptr); } + +#ifndef NDEBUG +DMNSN_LATE_DESTRUCTOR static void +dmnsn_leak_check(void) +{ + if (dmnsn_allocs > 0) { + dmnsn_warning("Leaking memory."); + } +} +#endif -- cgit v1.2.3