📄 heap.c
字号:
#include "struct.h"
#define HEAP_START 0x30000000
#define HEAP_END 0x33000000
#define UNUSED 0
#define USED 1
#define HEAP_NOTFIND 0
#define HEAP_FOUND 1
typedef struct heap{
int size;
int start;
int end;
int used;
struct heap *next;
struct heap *prv;
}heap;
static heap *heap_head;
static heap *heap_crrunt;
static heap *heap_mark;
//初始化堆
void init_heap()
{heap_head=(heap *)HEAP_START;
heap_head->size=(HEAP_START-HEAP_END+1)-sizeof(heap);
heap_head->start=HEAP_START+sizeof(heap);
heap_head->end=HEAP_END;
heap_head->used=UNUSED;
heap_head->next=NULL;
heap_head->prv=NULL;
heap_crrunt=heap_head;
}
//分配内存函数
void * xmalloc(unsigned int size)
{heap *newblock;
heap *prtblock;
int stat=HEAP_NOTFIND;
size=(size+7)&~7;
heap_mark=heap_crrunt;
while(heap_crrunt->next!=heap_mark)
{if(heap_crrunt==NULL) heap_crrunt=heap_head;
if(heap_crrunt->used==UNUSED)
{if(heap_crrunt->size>size)
{newblock=(heap*)((unsigned char *)heap_crrunt+(size+sizeof(heap)));
newblock->size=heap_crrunt->size-(size+sizeof(heap));
newblock->start=heap_crrunt->start+(size+sizeof(heap));
newblock->end=heap_crrunt->end;
newblock->used=UNUSED;
newblock->next=heap_crrunt->next;
newblock->prv=heap_crrunt;
heap_crrunt->used=USED;
heap_crrunt->size=size;
heap_crrunt->end=heap_crrunt->start+size;
heap_crrunt->next=newblock;
stat=HEAP_FOUND;
break;
}
}
heap_crrunt=heap_crrunt->next;
}
if(stat==HEAP_NOTFIND)
{return NULL;
}
prtblock=heap_crrunt;
heap_crrunt=newblock;
return (prtblock+sizeof(heap));
}
//释放
void xfree(void *block)
{heap * ptrblock;
heap * prvblock;
heap * nextblock;
if(block==NULL) return ;
ptrblock=(heap *)((unsigned char *)block-sizeof(heap));
ptrblock->used=UNUSED;
prvblock=ptrblock->prv;
nextblock=ptrblock->next;
if(prvblock!=NULL)
{if(prvblock->used==UNUSED)
{prvblock->size=prvblock->size+ptrblock->size+sizeof(heap);
prvblock->end=ptrblock->end;
prvblock->next=ptrblock->next;
ptrblock=prvblock;
}
}
if(nextblock!=NULL)
{if(nextblock->used==UNUSED)
{ptrblock->size=ptrblock->size+nextblock->size+sizeof(heap);
ptrblock->end=nextblock->end;
ptrblock->next=ptrblock->next;
}
}
heap_crrunt=ptrblock;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -