summaryrefslogtreecommitdiffstats
path: root/libdimension/malloc.c
diff options
context:
space:
mode:
authorTavian Barnes <tavianator@gmail.com>2011-05-16 23:44:06 -0600
committerTavian Barnes <tavianator@gmail.com>2011-05-16 23:44:06 -0600
commita932d4f46c2fadd6c750d844846fb9ba4baf45e0 (patch)
tree6f459c60433752713a74f84c8dddd1004037c91d /libdimension/malloc.c
parentd374841194f24c7cb1cdc52fc631fcb2982af358 (diff)
downloaddimension-a932d4f46c2fadd6c750d844846fb9ba4baf45e0.tar.xz
Add basic leak check.
Diffstat (limited to 'libdimension/malloc.c')
-rw-r--r--libdimension/malloc.c33
1 files changed, 32 insertions, 1 deletions
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 <stdlib.h>
#include <string.h>
+#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