-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmem.c
More file actions
71 lines (53 loc) · 1.3 KB
/
mem.c
File metadata and controls
71 lines (53 loc) · 1.3 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
#include <stdint.h>
#include <textmode.h>
#include <mem.h>
uint8_t buffer[MEM_BUFFER_SIZE];
struct alloc_head* root;
static void* init_root_alloc_head(void* p, uint32_t size)
{
void* addr = p;
while (root->next) {
addr += root->size;
root->next = (struct alloc_head*)addr;
root = root->next;
}
root = (struct alloc_head*)addr;
root->size = size;
root->status = BLOCK_STATUS_RESERVED;
return root + sizeof(struct alloc_head);
}
void* malloc(uint32_t size)
{
if (!root) {
return init_root_alloc_head(buffer, size);
}
return init_root_alloc_head(buffer, size);
}
void* calloc(uint32_t n, uint32_t size)
{
void* new = malloc(n * size);
for (int b = 0; b < n * size; b++) {
((uint32_t*)new)[b] = 0;
}
return new;
}
void* realloc(void* p, uint32_t size)
{
if (!p) {
return malloc(size);
}
struct alloc_head* head = (struct alloc_head*)(p - sizeof(struct alloc_head));
if (!head) {
// pointer was a fake allocation
return NULL;
}
void* new = malloc(size);
if (!new) {
return NULL;
}
uint32_t copy_size = size > head->size ? size : head->size;
for (int b = 0; b < copy_size; b++) {
((uint32_t*)new)[b] = ((uint32_t*)p)[b];
}
return new;
}