-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryChecker.c
More file actions
69 lines (62 loc) · 1.29 KB
/
Copy pathMemoryChecker.c
File metadata and controls
69 lines (62 loc) · 1.29 KB
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
/*
* Memory.c
*
* Created on: May 20, 2016
* Author: Moawiya
*/
#include "MemoryChecker.h"
static Memory m;
static bool init;
struct _memoryCheck_t {
int size;
unsigned int allocsNum;
unsigned int freesNum;
unsigned int totalAllocated;
bool* initialized;
};
void initMemory() {
m.size = 0;
m.allocsNum = 0;
m.freesNum = 0;
m.totalAllocated = 0;
m.initialized = &init;
}
void* allocate(size_t size) {
if (m.initialized != &init) {
printf("Memory is not initialized !!!\n");
exit(1);
}
void* pntr = malloc(size);
if (pntr == NULL) {
return NULL;
}
m.size += size;
m.totalAllocated += size;
m.allocsNum++;
return pntr;
}
void deallocate(void* pntr, size_t size) {
if (m.initialized != &init) {
printf("Memory is not initialized !!!\n");
exit(1);
}
if (pntr == NULL) {
return;
}
m.size -= size;
m.freesNum++;
free(pntr);
}
void finishMemory() {
char *line = "===========================================================";
printf("HEAP SUMMARY:\n%s\n", line);
if (m.size == 0) {
printf("All heap blocks were freed -- no leaks are possible\n");
} else {
printf("%d bytes leaked !!!\n", m.size);
}
printf("total heap usage: %u allocs, %u frees, %u bytes allocated\n",
m.allocsNum, m.freesNum, m.totalAllocated);
printf("%s\n", line);
m.initialized = NULL;
}