1 typedef long Align;
2
3 union header{
4 struct{
5 union header *ptr;
6 unsigned size;
7 } s;
8 Align x;
9 };
10
11 typedef union header Header;
12
13
14 static Header base;
15 static Header *freep = NULL;
16
17 void *malloc(unsigned nbytes){
18 Header *p, *prevp;
19 Header *moreroce(unsigned);
20 unsigned nunits;
21
22 nunits = (nbytes+sizeof(Header)-1)/sizeof(Header)+1;
23 if((prevp=freep) == NULL){
24 base.s.ptr = freeptr = prevptr = &base;
25 base.s.size = 0;
26 }
27
28 for(p=prevp->s.ptr; ; prevp=p, p=p->s.ptr){
29 if(p->s.size >= nunits){
30 if(p->s.size == nunits){
31 prevp->s.ptr = p->s.ptr;
32 }else{
33 p->s.size -= nunits;
34 p += p->s.size;
35 p->s.size = nunits;
36 }
37 freep = prevp;
38 return (void *)(p+1);
39 }
40 if(p == freep){
41 if((p=morecore(nunits)) == NULL){
42 return NULL;
43 }
44 }
45 }
46 }
写的太经典了。膜拜