-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleakfinder.c
executable file
·98 lines (86 loc) · 2.05 KB
/
leakfinder.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#define KEY_STR_MAX (128)
#define BUCKET_SIZE (127)
typedef struct _ENTRY {
int used;
char key[KEY_STR_MAX];
int count;
} T_ENTRY;
T_ENTRY buckets[BUCKET_SIZE];
static int hash(const char *key) {
int val = 0;
int offset = 1;
char *pKey = (char *)key;
while(*pKey) {
val ^= (*pKey * *pKey);
val <<= offset;
offset++;
pKey++;
}
#if DEBUG
fprintf(stdout, "[DEBUG] key:[%s] val:[%d]\n", key, val);
#endif
return val % BUCKET_SIZE;
}
int check_collision(int len, char **keys) {
int i = 0;
int idx;
for(i = 0; i < len; i++) {
idx = hash(keys[i]);
fprintf(stdout, "func:[%s] idx:[%d]\n", keys[i], idx);
if (buckets[idx].used == 0) {
buckets[idx].used = 1;
} else {
fprintf(stderr, "collision detected\n");
return -1;
}
}
return 0;
}
int init_leakfinder(void) {
memset(buckets, 0, sizeof(T_ENTRY) * BUCKET_SIZE);
return 0;
}
void show_result(void) {
int i;
fprintf(stderr, "------------------- allocated results ------------------------\n");
for (i = 0; i < BUCKET_SIZE; i++) {
if (buckets[i].used) {
fprintf(stderr, "function:[%s] unreleased:[%d]\n", buckets[i].key, buckets[i].count);
}
}
fprintf(stderr, "------------------- allocated results ------------------------\n");
fprintf(stderr, "\n");
}
void *my_malloc(char *func, size_t size) {
void *p;
int idx = hash(func);
if (buckets[idx].used == 0) {
// called first time
buckets[idx].used = 1;
strcpy(buckets[idx].key, func);
buckets[idx].count = 1;
} else {
buckets[idx].count++;
}
p = malloc(size);
return p;
}
void my_free(char *func, void *p) {
int idx = hash(func);
if (buckets[idx].used == 0) {
fprintf(stderr, "free called for not allocated in:%s, addr:[%p]\n", func, p);
assert(0);
} else {
if (0 < buckets[idx].count) {
buckets[idx].count--;
} else {
fprintf(stderr, "double free in:%s, addr:[%p]\n", func, p);
assert(0);
}
}
free(p);
}