This repository has been archived by the owner on Jun 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmalloc.c
120 lines (97 loc) · 2.81 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
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
#include <stdio.h>
#include <stdlib.h>
#define MAXBYTES (unsigned)10240
#define NALLOC 1024
typedef long Align;
union header {
struct {
union header *ptr; /* next block if on free list */
unsigned size; /* size of this block */
} s;
};
typedef union header Header;
static unsigned maxalloc; /* max number of units allocated */
static Header base; /* empty list to get started */
static Header *freep = NULL; /*start of free list */
/* morecore: ask system for more memory */
static Header *morecore(unsigned nu) {
char *cp, *sbrk(int);
Header *up;
if (nu < NALLOC)
nu = NALLOC;
cp = sbrk(nu * sizeof(Header));
if (cp == (char *) -1) /* no space at all */
return NULL;
up = (Header *) cp;
up->s.size = nu;
free((void *)(up + 1));
return freep;
}
/* malloc: general purpose storage allocator */
void *mallocx(unsigned nbytes) {
Header *p,*prevp;
Header *morecore(unsigned);
unsigned nunits;
if (nbytes > MAXBYTES) {
fprintf(stderr,"alloc: can't allocate more than %u bytes\n",MAXBYTES);
return NULL;
}
nunits = (nbytes + sizeof(Header) -1) / sizeof(Header) +1;
if ((prevp = freep) == NULL) {
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for (p = prevp->s.ptr ; ; prevp = p,p = p ->s.ptr) {
if (p->s.size >= nunits) {
if (p->s.size == nunits)
prevp->s.ptr = p->s.ptr;
else {
p->s.size -= nunits;
p += p->s.size;
p->s.size = nunits;
}
freep = prevp;
return (void *)(p+1);
}
if (p == freep) /* wrapped around free list */
if ((p = morecore(nunits)) == NULL)
return NULL;
}
}
/* free: put a block ap in free list */
void free(void *ap) {
Header *bp, *p;
bp = (Header *)ap - 1; /* point to block header */
for (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
if (p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break; /* freed block at start or end of arena */
if (bp + bp->s.size == p->s.ptr) { /* join to upper nbr */
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
if (p + p->s.size == bp) { /* join to lower nbr */
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
freep = p;
}
int main(void) {
int *p = NULL;
int i = 0;
p = mallocx(1000);
if (NULL == p) {
printf("mallocx returned NULL");
} else {
for (i = 0; i <= 100; i++) {
printf("%08X", p[i]);
if (i % 8 == 7) {
printf("\n");
}
}
printf("\n");
free(p);
}
return 0;
}