-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemleak3.c
57 lines (37 loc) · 930 Bytes
/
memleak3.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
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <malloc.h>
#include <mcheck.h>
void *malloc_hook(size_t size, const char *file, int line) {
void *p = malloc(size);
char buff[128] = {0};
sprintf(buff, "./mem/%p.mem",p);
FILE *fp = fopen(buff, "w");
fprintf(fp, "c/cpp:%s,line:%d --> addr:%p, size:%ld\n", file, line, p, size);
fflush(fp);
fclose(fp);
return p;
}
void free_hook(void *p, const char *file, int line) {
char buff[128] = {0};
sprintf(buff, "./mem/%p.mem", p);
if (unlink(buff) < 0) { // 多次关闭
printf("double free: %p\n", p);
return ;
}
free(p);
}
#define malloc(size) malloc_hook(size, __FILE__, __LINE__)
#define free(p) free_hook(p, __FILE__, __LINE__)
int main(){
void *p1 = malloc(10);
void *p2 = malloc(20); //calloc, realloc
free(p1);
void *p3 = malloc(20);
void *p4 = malloc(20);
free(p2);
free(p4);
printf("a");
return 0;
}