-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmalloc.c
More file actions
131 lines (114 loc) · 2.59 KB
/
malloc.c
File metadata and controls
131 lines (114 loc) · 2.59 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <pthread.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
typedef char ALIGN[16];
typedef union header {
struct {
size_t size;
bool is_free;
union header *next;
} s;
ALIGN stub;
} header_t;
pthread_mutex_t global_malloc_lock;
header_t *head, *tail;
header_t *get_free_block(size_t size) {
header_t *current = head;
while (current) {
if (current->s.is_free && current->s.size >= size)
return current;
current = current->s.next;
}
return NULL;
}
void *mem_malloc(size_t size) {
void *memblock;
header_t *header;
if (!size)
return NULL;
pthread_mutex_lock(&global_malloc_lock);
header = get_free_block(size);
if (header) {
header->s.is_free = 0;
pthread_mutex_unlock(&global_malloc_lock);
return (void *)(header + 1);
}
size_t totalsize = sizeof(header_t) + size;
memblock = sbrk(totalsize);
if (memblock == (void *)-1) {
pthread_mutex_unlock(&global_malloc_lock);
return NULL;
}
header = memblock;
header->s.size = size;
header->s.is_free = false;
header->s.next = NULL;
if (!head) {
head = header;
}
if (tail)
tail->s.next = header;
tail = header;
pthread_mutex_unlock(&global_malloc_lock);
return (void *)(header + 1);
}
void mem_free(void *memblock) {
header_t *header, *tmp;
void *prog_break;
if (!memblock)
return;
pthread_mutex_lock(&global_malloc_lock);
header = (header_t *)memblock - 1;
prog_break = sbrk(0);
if ((char *)memblock + header->s.size == prog_break) {
if (head == tail) {
head = tail = NULL;
} else {
tmp = head;
while (tmp) {
if (tmp->s.next == tail) {
tmp->s.next = NULL;
tail = tmp;
}
tmp = tmp->s.next;
}
}
sbrk(0 - sizeof(header_t) - header->s.size);
pthread_mutex_unlock(&global_malloc_lock);
return;
}
header->s.is_free = true;
pthread_mutex_unlock(&global_malloc_lock);
}
void *mem_calloc(size_t num, size_t size) {
size_t tsize;
void *memblock;
if (!num || !size)
return NULL;
tsize = num * size;
if (size != tsize / num)
return NULL;
memblock = mem_malloc(tsize);
if (!memblock)
return NULL;
memset(memblock, 0, size);
return memblock;
}
void *mem_realloc(void *memblock, size_t size) {
header_t *header;
void *ret; // unknown
if (!memblock || !size)
return mem_malloc(size);
header = (header_t *)memblock - 1;
if (header->s.size >= size) {
return memblock;
}
ret = mem_malloc(size);
if (ret) {
memcpy(ret, memblock, header->s.size);
mem_free(memblock);
}
return ret;
}