-
Notifications
You must be signed in to change notification settings - Fork 0
/
mallok.c
107 lines (80 loc) · 2.02 KB
/
mallok.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
#define MALLOK_MACROS
#include "mallok.h"
#include <stdio.h>
#define MALLOK_DEBUG 0
typedef struct node *Node;
struct node {
size_t size;
int line;
char *file;
void *ptr;
Node next;
};
Node head = NULL;
Node tail = NULL;
static Node newNode(size_t size, char * file, int line, void *ptr);
void *mallokMalloc(size_t size, char *file, int line) {
void *ptr = malloc(size);
if (ptr == NULL) {
return NULL;
}
#if MALLOK_DEBUG
printf("%s:%d allocated %ld bytes\n", file, line, size);
#endif
Node new = newNode(size, file, line, ptr);
if (head == NULL) {
head = new;
tail = new;
return ptr;
}
tail->next = new;
return ptr;
}
void mallokFree(void *ptr) {
if (ptr == NULL) {
return;
}
if (head == NULL) {
printf("Nothing allocated?\n");
}
if (head->ptr == ptr) {
#if MALLOK_DEBUG
printf("%s:%d %ld bytes were freed\n", head->file, head->line, head->size);
#endif
free(head);
head = NULL;
tail = NULL;
return;
}
Node curr = head;
while(curr->next != NULL && curr->next->ptr != ptr) {
curr = curr->next;
}
// 2 cases: curr->next = NULL. curr->next->ptr == ptr
if (curr->next == NULL) {
printf("Couldnt find memory\n");
}
Node temp = curr->next;
curr->next = curr->next->next;
#if MALLOK_DEBUG
printf("%s:%d %ld bytes were freed\n", temp->file, temp->line, temp->size);
#endif
free(temp);
free(ptr);
}
void mallok() {
Node curr = head;
while (curr != NULL) {
printf("%s:%d %ld bytes not freed\n", curr->file, curr->line, curr->size);
curr = curr->next;
}
}
static Node newNode(size_t size, char * file, int line, void *ptr) {
Node new = malloc(sizeof(*new));
new->size = size;
new->file = file;
new->line = line;
new->ptr = ptr;
new->next = NULL;
return new;
}