-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamic_memory_ll.c
125 lines (87 loc) · 1.65 KB
/
dynamic_memory_ll.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
115
116
117
118
119
120
121
122
#include <stddef.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
typedef struct list_t list_t;
void free(void*);
struct list_t {
size_t size;
list_t* next;
char data[];
};
static list_t avail = { .next = NULL };
void* malloc(size_t size)
{
if (size == NULL)
return NULL;
list_t *p, *q;
p = &avail;
q = p->next;
while (q != NULL && q->size <= size) {
p = q;
q = q->next;
}
void* new_mem;
if (q == NULL) {
//No sufficiently large block found, ask kernel for more
new_mem = sbrk(size + sizeof(list_t));
if (new_mem == (void*) -1)
return NULL;
q = (list_t*) new_mem;
//p->next = q;
q->next = NULL;
q->size = size;
} else {
p->next = q->next;
q->next = NULL;
}
return q->data;
}
void* calloc(size_t nmemb, size_t size)
{
void* alloc_mem;
alloc_mem = malloc(nmemb * size);
memset(alloc_mem, 0, nmemb * size);
return alloc_mem;
}
void* realloc(void *ptr, size_t size)
{
if (ptr == NULL) {
return malloc(size);
} else if (size == 0) {
free(ptr);
return NULL;
}
list_t* r = ptr - sizeof(list_t);
if (r->size >= size) { //reduce size of memory
if (r->size - size <= 3 * sizeof(list_t)) {
//Its not worth it
return ptr;
} else {
void* mem = malloc(size);
memcpy(mem, r->data, size);
free(ptr);
return mem;
}
} else { //increase size of memory
void* mem = malloc(size);
memcpy(mem, r->data, r->size);
free(ptr); //VÄL?
return mem;
}
}
void free(void* ptr)
{
if (ptr == NULL)
return;
list_t* r = (void*)ptr - sizeof(list_t);
list_t *p, *q;
p = &avail;
q = p->next;
while (q != NULL) {
p = q;
q = q->next;
}
p->next = r;
r->next = NULL;
}