-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory_leak.h
64 lines (58 loc) · 1.49 KB
/
memory_leak.h
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
#include <stdlib.h>
#include <stdio.h>
int allocated_memory = 0;
void *all_memory[2000];
int all_memory_sizes[2000];
int all_memory_count;
void *_alloc(int count, int size){
auto result = calloc(count, size);
allocated_memory += count * size;
all_memory[all_memory_count] = result;
all_memory_sizes[all_memory_count] = count * size;
all_memory_count++;
return result;
}
void _free(void *memory){
free(memory);
for(int i=0; i<all_memory_count; i++) {
if(all_memory[i] == memory){
allocated_memory -= all_memory_sizes[i];
all_memory_count--;
all_memory_sizes[i] = all_memory_sizes[all_memory_count];
all_memory[i] = all_memory[all_memory_count];
return;
}
}
printf("Bad free\n");
}
void *_realloc(void *memory, int size){
allocated_memory += size;
auto result = realloc(memory, size);
if(!memory) {
all_memory[all_memory_count] = result;
all_memory_sizes[all_memory_count] = size;
all_memory_count++;
} else {
for(int i=0; i<all_memory_count; i++) {
if(all_memory[i] == memory){
allocated_memory -= all_memory_sizes[i];
all_memory_sizes[i] = size;
all_memory[i] = result;
return result;
}
}
printf("Bad realloc\n");
}
return result;
}
#ifdef ENABLE_MEMORY_LEAK_HOOK
#define calloc _alloc
#define free _free
#define realloc _realloc
void dump_non_free_memory(){
printf("Allocated memory %d, %d\n", allocated_memory, all_memory_count);
}
#else
void dump_non_free_memory(){
}
#endif