-
Notifications
You must be signed in to change notification settings - Fork 0
/
memleak.c
93 lines (62 loc) · 1.54 KB
/
memleak.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
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <mcheck.h>
#if 1
void * _malloc(size_t size, const char *filename,int line){
void *p = malloc(size);
char buff[128] = {0};
sprintf(buff,"./mem/%p.mem",p);
FILE *fp = fopen(buff,"w");
fprintf(fp,"[+]%s:%d,addr: %p,size :%ld\n",filename,line,p,size);
fflush(fp);
fclose(fp);
return p;
}
void _free(void *p,const char *filename ,int line){
//printf("[-]%s:%d, %p\n",filename,line,p);
char buff[128] = {0};
sprintf(buff,"./mem/%p.mem",p);
if(unlink(buff)<0){
printf("double free :%p\n",p);
return ;
}
return free(p);
}
#define malloc(size) _malloc(size,__FILE__,__LINE__)
#define free(size) _free(size,__FILE__,__LINE__)
#else
typedef void *(*malloc_t) (size_t size);
typedef void (*free_t) (void *ptr)
malloc_t malloc_f = NULL;
free_t free_f = NULL;
void *malloc(size_t size){
printf("size: %ld\n",size);
return NULL;
}
void free(void *ptr) {
printf("ptr :%p\n",ptr);
}
static void init_hook(void) {
if(malloc_f == NULL){
malloc_f = (malloc_t)dlsym(RTLD_NEXT,"malloc");
}
if(free_f == NULL){
free_f = (free_t)dlsym(RTLD_NEXT,"free");
}
}
#endif
//export MALLOC_TRACE=./mem.txt
int main(){
//mtrace();
//setenv("MALLOC_TRACE","./mem.txt");
init_hook();
void *p1 = malloc(10); //_malloc(size,__FILE__,__LINE__)
void *p1 = malloc(15);
void *p1 = malloc(20);
free(p2);
free(p3);
//muntrace();
}