-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalls.c
106 lines (72 loc) · 1.42 KB
/
calls.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
#include <string.h>
#include "calls.h"
void *_sbrk(ptrdiff_t incr);
struct block *freehead = NULL;
struct block {
size_t size;
struct block *p;
struct block *n;
};
void *malloc(size_t size)
{
struct block *fb;
char *b;
size += sizeof(struct block);
size = (size & 0xfffffff8) + 0x8;
fb = freehead;
while (fb != NULL) {
if (fb->size >= size) {
if (fb->p != NULL)
fb->p->n = fb->n;
else
freehead = fb->n;
if (fb->n != NULL)
fb->n->p = fb->p;
return ((unsigned char *) fb + sizeof(struct block));
}
fb = fb->n;
}
if ((b = _sbrk(size)) == NULL)
return NULL;
*((size_t *) b) = size;
return (b + sizeof(struct block));
}
void free(void *ptr)
{
struct block *fb;
ptr -= sizeof(struct block);
fb = (struct block *) ptr;
fb->p = NULL;
fb->n = freehead;
freehead->p = fb;
freehead = fb;
for (fb = freehead; fb != NULL;) {
size_t sz;
sz = *((size_t *) fb);
if (((char * ) fb) + sz == _sbrk(0)) {
if (fb->p != NULL)
fb->p->n = fb->n;
else
freehead = fb->n;
if (fb->n != NULL)
fb->n->p = fb->p;
fb = fb->n;
_sbrk(-((ptrdiff_t) sz));
continue;
}
fb = fb->n;
}
}
void *realloc(void *ptr, size_t size)
{
void *old, *new;
size_t oldsz;
new = malloc(size);
if (ptr == NULL)
return new;
old = ptr - sizeof(struct block);
oldsz = *((size_t *) old) - sizeof(struct block);
memcpy(new, ptr, oldsz);
free(ptr);
return new;
}