欢迎来到天天文库
浏览记录
ID:38802883
大小:14.96 KB
页数:4页
时间:2019-06-19
《计算机操作系统内存分配源码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、#include#includeusingnamespacestd;#defineMEM_SIZE200staticcharmem[MEM_SIZE];#defineMINBLK16structblock{structblock*next;size_tlength;chardata[0];};staticstructblock*free_list=NULL;//free_list为空voidmalloc_init(void){free_list=(structbl
2、ock*)mem;free_list->next=NULL;//next指向空free_list->length=MEM_SIZE-sizeof(structblock);//data段的长度}//字节对齐void*malloc(size_tsize){size=(size+7)&~7;structblock*prev=(structblock*)&free_list;//block首段structblock*cur=free_list;//cur指向空闲的块while(cur!=NULL){if(c
3、ur->length>=size)//判断cur指向的块是否满足所要求的大小break;prev=cur;cur=cur->next;}if(cur==NULL)returnNULL;//cur->length(data段的长度)-size后的大小可不可以放下blockif((cur->length-size)>=MINBLK){structblock*temp=(structblock*)(cur->data+size);//temp指向新block的头temp->next=cur->next;//
4、新block指向下一个空白temp->length=cur->length-size-sizeof(structblock);prev->next=temp;cur->length=size;}else{prev->next=cur->next;}returncur->data;}voidfree(void*ptr){if(ptr==NULL)return;structblock*temp=(structblock*)((char*)ptr-sizeof(structblock));char*temp
5、n=(char*)ptr+temp->length;//和temp物理上相邻的下一个block的地址structblock*prev=(structblock*)&free_list;structblock*cur=free_list;char*curn;//和cur物理上相邻的下一个block的地址//考虑多种情况,完成free函数//......if(free_list>temp)//空块地址大于要释放的块的地址,直接将释放的块放入空白块头部(第一种情况){if(((char*)temp+size
6、of(block)+temp->length)==(char*)free_list){temp->length+=sizeof(block)+free_list->length;free_list=temp;}else{temp->next=free_list;free_list=temp;}ptr=NULL;return;}//若不一定插入头部,寻找插入块while(cur!=NULL&&(char*)cur<(char*)temp){prev=cur;cur=cur->next;}//temp与前
7、段free_list相邻if(((char*)prev+sizeof(structblock)+prev->length)==(char*)temp){prev->length=prev->length+sizeof(structblock)+temp->length;temp=prev;ptr=NULL;}else{prev->next=temp;ptr=NULL;}//free_list在比temp地址大的地方且两者相邻if((char*)tempn==(char*)cur
8、
9、cur==NULL)
10、{temp->next=cur->next;temp->length=sizeof(structblock)+cur->length+temp->length;ptr=NULL;}else{temp->next=cur;ptr=NULL;}}voidmalloc_state(void){printf("freeblocks:");structblock*ptr;for(ptr=free_list;ptr!=NULL;ptr=ptr->next){in
此文档下载收益归作者所有