-
Notifications
You must be signed in to change notification settings - Fork 0
/
mmdbg.c
83 lines (74 loc) · 1.64 KB
/
mmdbg.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "mmdbg.h"
static size_t total_alloc = 0;
static size_t total_free = 0;
static pthread_mutex_t mutex;
int memory_dbg_init()
{
TAILQ_INIT(&head);
total_alloc = total_free = 0;
return pthread_mutex_init(&mutex, NULL);
}
void* _malloc_dbg(size_t size)
{
void *ret = malloc(size);
if (ret) {
np = malloc(sizeof(struct entry)); /* Insert at the tail. */
np->p = ret;
np->size = size;
} else {
return NULL;
}
/*critical region*/
pthread_mutex_lock(&mutex);
total_alloc += size;
TAILQ_INSERT_TAIL(&head, np, entries);
pthread_mutex_unlock(&mutex);
return ret;
}
void _free_dbg(void* p)
{
/*critical region*/
pthread_mutex_lock(&mutex);
TAILQ_FOREACH(np, &head, entries)
{
if (np->p == p) {
total_free += np->size;
TAILQ_REMOVE(&head, np, entries);
free(np);
free(p);
pthread_mutex_unlock(&mutex);
return;
}
}
pthread_mutex_unlock(&mutex);
}
int memory_dbg_finalize()
{
pthread_mutex_lock(&mutex);
np = TAILQ_FIRST(&head);
if (np != NULL) {
printf("[%s:%s():%d] potential loss %ld bytes memory!\n", __FILE__, __FUNCTION__, __LINE__, (total_alloc - total_free));
}
while (np!= NULL) {
printf("[%s:%s():%d] potential memory leakage!!! np %p (ptr = %p, size = %lu)\n", __FILE__, __FUNCTION__, __LINE__, np, np->p, np->size);
TAILQ_REMOVE(&head, np, entries);
free(np->p);
np = TAILQ_NEXT(np, entries);
}
pthread_mutex_unlock(&mutex);
return pthread_mutex_destroy(&mutex);
}
static int _tailq_size()
{
int num = 0;
pthread_mutex_lock(&mutex);
TAILQ_FOREACH(np, &head, entries)
{
num++;
}
pthread_mutex_unlock(&mutex);
return num;
}