-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmem.c
More file actions
105 lines (85 loc) · 2.24 KB
/
mem.c
File metadata and controls
105 lines (85 loc) · 2.24 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
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
#include <stdint.h>
#include <stddef.h>
#include "mem.h"
#include "drivers/disp.h"
static uint8_t memoryarea[memsize]; //array we use uint8_t because its 1 byte long and makes lifer easier
static Node *start;
int allocate_first(){
start = (Node*) memoryarea;
start->flag = 0;
start->size = memsize - node_size;
start->next = NULLN;
start->prev = NULLN;
nl();
print_s("chunk for dynamic memory allocated at ");
char addr[10];
stringaddr((char*)start,addr);
print_s(addr);
nl();
return 0;
}
void* findsmallestfree(Node *memarea ,size_t size){
Node *bestblk = (Node*) NULLN;
uint32_t bestblks = memsize + 1;
Node *currblk = start;
while(currblk){
if((!currblk->flag)&&(currblk->size>=size+node_size)&&currblk->size<=bestblks){
bestblk = currblk;
bestblks = currblk->size;
}
currblk = currblk->next;
}
return bestblk;
}
void *alloc(size_t size){
Node *bestblk = (Node*) findsmallestfree(start,size);
if(bestblk != NULLN){
bestblk->size = bestblk->size - size - node_size;
Node *newnode = (Node*) (((uint8_t*) bestblk)+node_size + bestblk -> size);
// makes new node at address that is bestblk size + node size from the bestblk address
newnode->size = size;
newnode-> flag = 1;
newnode->next = bestblk->next;
newnode->prev = bestblk;
if(bestblk->next != NULLN){
bestblk->next->prev = newnode;//if there is a node after the bestblk make the prev node
//of that point to the new node we made
}
bestblk->next = newnode;
return (void*) ((uint8_t *)newnode + node_size);
}
return NULLN;
}
void freee (void *p){
if(p == NULLN){
return;
}
Node *curr = (Node*) ((uint8_t*)p - node_size);
if(curr == NULLN){
return;
}
curr->flag = 0;
curr = mergeprevchk(curr);
mergeprevchk(curr);
}
void *mergeprevchk(Node * curr){
Node *prevn = curr->prev;
if(prevn != NULLN && !prevn->flag){
prevn->size += curr->size + node_size;
prevn->next = curr->next;
if(curr->next != NULLN){
curr->next->prev = prevn;
}
}
return prevn;
}
void *mergenxtchk(Node *curr) {
Node *nxt = curr->next;
if (nxt != NULLN && !nxt->flag) {
curr->size += nxt->size + node_size;
curr->next = nxt->next;
if (nxt->next != NULLN) {
nxt->next->prev = curr;
}
}
}