c语言malloc汇编实现形式,手动实现malloc函数(c语言)
#include char memory[2000];struct block{size_t size;//区块大小int free;//是否已使用struct block *next;//指向下一个区块};struct block *freeList=(void *)memory;void init(){freeList->size=2000...
#include char memory[2000];
struct block{
size_t size; //区块大小
int free; //是否已使用
struct block *next; //指向下一个区块
};
struct block *freeList=(void *)memory;
void init()
{
freeList->size=2000-sizeof(struct block);//可用空间大小
freeList->free=1; //1:空闲 0:使用
freeList->next=NULL; //指向空
}
void split(struct block *fitting_slot,size_t size)
{
struct block *new=(void*)(fitting_slot+size+sizeof(struct block)); //定义new的地址
new->size=(fitting_slot->size)-size-sizeof(struct block); //定义size大小
new->free=1; //设置是否工作
new->next=fitting_slot->next; //独立出去,形成新的块
fitting_slot->size=size;
fitting_slot->free=0;
fitting_slot->next=new;
}
void *MyMalloc(size_t noOfBytes)
{
struct block *curr,*prev;
void *result;
if(!(freeList->size))
init();
curr=freeList;
while(((curr->sizefree==0))&&(curr->next!=NULL))
{
prev=curr;
curr=curr->next;
}
if(curr->size==noOfBytes)
{
curr->free=0;
result=(void*)(++curr);
return result;
}
else if(curr->size>noOfBytes+sizeof(struct block)) //所需要的内存大小小于区块大小
{
split(curr,noOfBytes); //分割区块函数
result=(void*)(++curr); //使用的位置
return result;
}
else
{
result=NULL;
return result;
}
}
void merge()
{
struct block *curr,*prev;
curr=freeList;
while(curr!=NULL&&curr->next!=NULL)
{
if(curr->free&&curr->next->free)
{
curr->size+=(curr->next->size)+sizeof(struct block);
curr->next=curr->next->next;
}
prev=curr;
curr=curr->next;
}
}
void MyFree(void* ptr)
{
if(((void*)memory<=ptr)&&(ptr<=(void*)(memory+2000)))
{
struct block* curr=ptr;
curr--;
curr->free=1;
merge();
}
else
return;
}
int main()
{
int *p,*q,n;
p=(int *)MyMalloc(sizeof(int));
q=(int *)MyMalloc(sizeof(int));
//p=(int *)malloc(sizeof(int));
scanf("%d",&n);
*p=n; *q=n+1;
printf("%d %d\n",*p,*q);
MyFree(p); MyFree(q);
//free(p);
return 0;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)