forked from Winderton/malloc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
150 lines (111 loc) · 2.16 KB
/
main.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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>
#define u8 uint8_t
#define u16 uint16_t
#define STACK_SIZE 32
#define HEAP_SIZE STACK_SIZE * 4
#define HEADER 4
static u16 IN_USE;
typedef struct virtual_memory
{
u8 stack[STACK_SIZE];
char** unmapped;
u8 heap[HEAP_SIZE];
struct
{
char** data;
char** bss;
char* text;
}data_t;
}virtual_memory_t;
typedef struct entity
{
u8* ptr;
int size;
}entity_t;
entity_t LIST[40];
void LOG()
{
printf("OUR LIST\n");
for (unsigned i = 0; i < IN_USE; i++)
{
printf("Data + HEADER. [%p]. Memory of our heap free: [%u]\n", LIST[i].ptr, LIST[i].size);
}
printf("Entities in use:[%d]\n", (sizeof(LIST) / sizeof(LIST[0]) - IN_USE));
}
entity_t* new_entity(size_t size)
{
if (LIST[0].ptr == NULL && LIST[0].size == 0)
{
static virtual_memory_t vm;
LIST[0].ptr = vm.heap;
LIST[0].size = HEAP_SIZE;
IN_USE++;
LOG();
}
entity_t* best = LIST;
for (unsigned i = 0; i < IN_USE; i++)
{
if (LIST[i].size >= size && LIST[i].size < best->size)
{
best = &LIST[i];
}
}
return best;
}
void* w_malloc(size_t size)
{
assert(size <= HEAP_SIZE);
size += HEADER;
entity_t* e = new_entity(size);
u8* start = e->ptr;
u8* user_ptr = start + HEADER;
*start = size;
e->ptr += size;
e->size -= size;
assert(e->size >= 0);
LOG();
return user_ptr;
}
void w_free(void* ptr)
{
u8* start = (u8*)ptr - HEADER;
LIST[IN_USE].ptr = &(*start);
LIST[IN_USE].size = (u8)*((u8*)ptr - HEADER);
IN_USE++;
LOG();
}
void test()
{
typedef struct foo
{
int a;
int b;
}foo_t;
foo_t* foo;
int* bazz;
char* bar;
foo = w_malloc(sizeof(foo_t));
bar = w_malloc(5);
bazz = w_malloc(sizeof(int));
foo->a = 5;
foo->b = 10;
strcpy(bar, "bar");
memcpy(bazz, &foo->a, sizeof(int));
printf("Address: [%p], data: [%d] [%d]\n", foo, foo->a, foo->b);
printf("Address: [%p], data: [%s] \n", bar, bar);
printf("Address: [%p], data: [%d] \n", bazz, *bazz);
w_free(foo);
w_free(bar);
char* other = w_malloc(96);
strcpy(other, "other");
printf("Address: [%p], data: [%s] \n", other, other);
}
int main(int argc, char** argv)
{
test();
return 0;
}