summaryrefslogtreecommitdiff
path: root/utils.c
diff options
context:
space:
mode:
Diffstat (limited to 'utils.c')
-rw-r--r--utils.c68
1 files changed, 42 insertions, 26 deletions
diff --git a/utils.c b/utils.c
index b9a4bed..08a5464 100644
--- a/utils.c
+++ b/utils.c
@@ -14,57 +14,72 @@ static int malloc_count = 0;
LIST_HEAD(malloc_list);
struct allocation {
- void *caller;
+ const char *allocfn;
+ const char *callerfn;
+ int line;
void *ptr;
size_t size;
struct list_head list;
};
static void
-__add_allocation(void *caller, void *ptr, size_t size)
+add_allocation(const char *allocfn, const char *callerfn, int line, void *ptr, size_t size)
{
struct allocation *a = malloc(sizeof(*a));
- a->caller = caller;
+ fprintf(stderr, "Allocation: %s:%i %s(%zu) = %p\n",
+ callerfn, line, allocfn, size, ptr);
+ a->allocfn = allocfn;
+ a->callerfn = callerfn;
+ a->line = line;
a->ptr = ptr;
a->size = size;
list_add(&a->list, &malloc_list);
+ total_malloc_count++;
+ malloc_count++;
}
-#define add_allocation(p, s) __add_allocation(__builtin_extract_return_addr(__builtin_return_address(0)), p, s)
-
void *
-__zmalloc(size_t size)
+__zmalloc(const char *fn, int line, size_t size)
{
void *ptr;
- fprintf(stderr, "zmalloc: Allocation size %zi\n", size);
ptr = calloc(1, size);
- if (ptr) {
- add_allocation(ptr, size);
- total_malloc_count++;
- malloc_count++;
- }
+ if (ptr)
+ add_allocation("zmalloc", fn, line, ptr, size);
+ else
+ perrordie("zmalloc");
return ptr;
}
char *
-__xstrdup(const char *s)
+__xstrdup(const char *fn, int line, const char *s)
{
- char *r;
-
- fprintf(stderr, "xstrdup: Allocation size %zi\n", strlen(s) + 1);
- r = strdup(s);
- if (r) {
- add_allocation(r, strlen(s) + 1);
- total_malloc_count++;
- malloc_count++;
- }
- return r;
+ char *ptr;
+
+ ptr = strdup(s);
+ if (ptr)
+ add_allocation("xstrdup", fn, line, ptr, strlen(s) + 1);
+ else
+ perrordie("strdup");
+ return ptr;
+}
+
+char *
+__xstrndup(const char *fn, int line, const char *s, size_t n)
+{
+ char *ptr;
+
+ ptr = strndup(s, n);
+ if (ptr)
+ add_allocation("xstrndup", fn, line, ptr, n);
+ else
+ perrordie("strndup");
+ return ptr;
}
void
-xfree(void *ptr)
+__xfree(const char *fn, int line, void *ptr)
{
struct allocation *a, *tmp;
unsigned delete_count = 0;
@@ -74,6 +89,7 @@ xfree(void *ptr)
free(ptr);
malloc_count--;
+ fprintf(stderr, "Deallocation: %s:%i %p\n", fn, line, ptr);
list_for_each_entry_safe(a, tmp, &malloc_list, list) {
if (a->ptr == ptr) {
list_del(&a->list);
@@ -97,8 +113,8 @@ debug_resource_usage()
malloc_count, total_malloc_count);
list_for_each_entry(a, &malloc_list, list) {
- fprintf(stderr, "* Allocation - caller: 0x%p, ptr: 0x%p, size %zu\n",
- a->caller, a->ptr, a->size);
+ fprintf(stderr, "* Lost allocation - %s:%i - ptr: %p, size: %zu\n",
+ a->callerfn, a->line, a->ptr, a->size);
}
}