-
Notifications
You must be signed in to change notification settings - Fork 0
/
malloc.c
114 lines (84 loc) · 1.69 KB
/
malloc.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static size_t mallocs;
static size_t frees;
static size_t total_malloc_size;
static void check_memory_leaks(void)
{
size_t leaks;
FILE* heap;
heap = fopen("heap", "w");
if (heap != NULL) {
fprintf(heap, "%zu\n", total_malloc_size);
fclose(heap);
}
leaks = mallocs-frees;
if (leaks == 0)
return;
fprintf(stderr, "----------------------------------------------\n");
if (frees > mallocs) {
fprintf(stderr, "undefined behavior detected: more frees (%zu) than allocations (%zu)\n",
frees, mallocs);
} else {
fprintf(stderr, "fatal program error detected: memory leak");
fprintf(stderr, "\nnumber of allocations in use: %15zu\n", mallocs-frees);
}
fprintf(stderr, "\ngoodbye, terminating abnormally...\n");
fprintf(stderr, "----------------------------------------------\n");
abort();
}
static void init(void)
{
static unsigned char initialized;
if (initialized)
return;
atexit(check_memory_leaks);
initialized = 1;
}
void* __check_malloc(size_t s)
{
void* p;
char* t;
size_t i;
if (s == 0)
return NULL;
init();
p = malloc(s);
if (p != NULL) {
total_malloc_size += s;
mallocs += 1;
t = p;
// for (i = 0; i < s; i += 1)
// t[i] = rand();
}
return p;
}
void* __check_calloc(size_t s, size_t n)
{
void* p;
size_t total;
total = s * n;
p = __check_malloc(total);
if (p == NULL)
return NULL;
memset(p, 0, total);
return p;
}
void __check_free(void* p)
{
if (p != NULL) {
frees += 1;
free(p);
}
}
void* __check_realloc(void* p, size_t s)
{
if (s == 0) {
__check_free(p);
return NULL;
} else if (p == NULL)
return __check_malloc(s);
else
return realloc(p, s);
}