-
Notifications
You must be signed in to change notification settings - Fork 1
/
malloc.c
58 lines (52 loc) · 1.27 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
/*
** EPITECH PROJECT, 2019
** PSU_2018_malloc
** File description:
** bttfmalloc
*/
#include "malloc.h"
header_malloc_t *look_for_available_memory(size_t size)
{
header_malloc_t *temp = start;
while (temp != NULL) {
if (temp->is_free && temp->size >= size)
return (temp);
temp = temp->next;
}
return (NULL);
}
header_malloc_t *update_header (header_malloc_t *header, size_t size, void *memory_block)
{
header = memory_block;
header->size = size;
header->is_free = false;
header->next = NULL;
if (!start)
start = header;
if (end)
end->next = header;
end = header;
pthread_mutex_unlock(&lock);
return (header);
}
void *malloc(size_t size)
{
void *memory_block;
header_malloc_t *header;
pthread_mutex_lock(&lock);
if (!size)
return (NULL);
header = look_for_available_memory(size);
if (header != NULL) {
header->is_free = false;
pthread_mutex_unlock(&lock);
return (void*)(header + 1);
}
memory_block = sbrk((sizeof(header_malloc_t) + size));
if (memory_block == (void*) - 1) {
pthread_mutex_unlock(&lock);
return (NULL);
}
header = update_header(header, size, memory_block);
return (void*)(header + 1);
}