-
Notifications
You must be signed in to change notification settings - Fork 1
/
malloc.c
95 lines (83 loc) · 1.63 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
/*
** EPITECH PROJECT, 2021
** B-PSU-400-LYN-4-1-malloc-thibault.bordenave
** File description:
** malloc
*/
#include "libmalloc.h"
chunk_t *head;
chunk_t *best_fit(size_t size, chunk_t *last)
{
chunk_t *base;
if (!head)
return NULL;
base = head;
while (base->size < size || base->free == false)
{
base = base->next;
if (base == head)
return NULL;
}
return base;
}
chunk_t *new_alloc(size_t size)
{
chunk_t *new;
void *ptr;
ptr = sbrk(size);
if (ptr == (void *)-1)
return NULL;
new = ptr;
new->size = size - sizeof(chunk_t);
new->to_use = ptr + sizeof(chunk_t);
new->free = true;
new->next = NULL;
new->prev = NULL;
return new;
}
void append(chunk_t *chunk)
{
chunk_t *base;
if (!head)
head = chunk;
base = head;
while (base < chunk)
{
base = base->next;
if (base == head)
break;
}
chunk->prev = base->prev;
chunk->next = base;
base->prev = chunk;
base->prev->next = chunk;
}
size_t block_size(size_t size)
{
int i = 1;
size = size + sizeof(chunk_t);
i = i + size / page_size();
return page_size() * i;
}
void *malloc(size_t size)
{
chunk_t *mem;
if (size <= 0)
return NULL;
mem = best_fit(size, mem);
if (!mem)
{
mem = new_alloc(block_size(size));
if (!mem)
return NULL;
else {
append(mem);
split(mem, size);
return mem->to_use;
}
}
if (mem->size > size)
split(mem, size);
mem->free = false;
return mem->to_use;
}