欢迎来到天天文库
浏览记录
ID:47561153
大小:25.00 KB
页数:4页
时间:2020-01-15
《计算机操作系统内存分配源码》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
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=(structblock*)mem;fre
2、e_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(cur->length>=size)//判断cur
3、指向的块是否满足所要求的大小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;//新block指向下一个空白temp->length=cur->lengt
4、h-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*tempn=(char*)ptr+temp->length;//和temp物理上相邻的
5、下一个block的地址structblock*prev=(structblock*)&free_list;structblock*cur=free_list;char*curn;//和cur物理上相邻的下一个block的地址//考虑多种情况,完成free函数//......if(free_list>temp)//空块地址大于要释放的块的地址,直接将释放的块放入空白块头部(第一种情况){if(((char*)temp+sizeof(block)+temp->length)==(char*)free_list){temp->le
6、ngth+=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与前段free_list相邻if(((char*)prev+sizeof(structblock)+prev->length)==
7、(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)最新范本,供参考!{temp->next=cur->next;temp->length=sizeof(structblock)+cur->length
10、+temp->length;ptr=NULL;}else{temp->next=cur;ptr=NULL;}}voidmalloc_state(void){printf("freeblocks:");structblock*ptr;for(ptr=free_list;ptr!=NULL
此文档下载收益归作者所有