欢迎来到天天文库
浏览记录
ID:12411913
大小:29.00 KB
页数:7页
时间:2018-07-16
《malloc的工作原理》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、malloc的工作原理该函数演示了malloc的工作原理:1.malloc在一块平台的内存区管理内存(可以称之为堆)2.malloc由管理块和数据块构成3.malloc首先以链表的方式搜索已管理的内存,没有找到,再从大池里扩展一块进入valid_address管理区*/#include#include#include#defineSIZE0x10000structmem_control_block{intis_available;intsize;
2、};inthas_initialized=0;void*g_managed_memory_start;void*g_last_valid_address;voidmalloc_init();voidmyfree(void*firstbyte);void*mymalloc(longnumbytes);voidsimu_init(void){g_last_valid_address=malloc(SIZE);}voidsbrk(intn){/*它的愿意是内存不够了,向系统追加申请内存,由系统连接为一块平坦
3、的内存在我们的模拟中,已经是一块平坦的内存,所以此函数没有意义*/if(((int)g_last_valid_address+n)>(int)g_managed_memory_start+SIZE){printf("memoryfull!");exit(1);}}intmain(void){void*p1,*p2,*p3,*p4,*p5;simu_init();p1=mymalloc(0x100);p2=mymalloc(0x200);p3=mymalloc(0x300);printf("p1of
4、fset:%x",(char*)p1-(char*)g_managed_memory_start);printf("p2offset:%x",(char*)p2-(char*)g_managed_memory_start);printf("p3offset:%x",(char*)p3-(char*)g_managed_memory_start);myfree(p2);p4=mymalloc(0x50);p5=mymalloc(0x50);printf("p4offset:%x",(ch
5、ar*)p4-(char*)g_managed_memory_start);printf("p5offset:%x",(char*)p5-(char*)g_managed_memory_start);myfree(p1);myfree(p3);myfree(p4);myfree(p5);system("pause");return0;}voidmalloc_init(){/*grabthelastvalidaddressfromtheOS*///g_last_valid_address=sbrk(
6、0);/*wedon'thaveanymemorytomanageyet,so*justsetthebeginningtobeg_last_valid_address*/g_managed_memory_start=g_last_valid_address;/*Okay,we'reinitializedandreadytogo*/has_initialized=1;}voidmyfree(void*firstbyte){structmem_control_block*mcb;/*Backupfromt
7、hegivenpointertofindthe*mem_control_block*/mcb=(structmem_control_block*)((int)firstbyte-sizeof(structmem_control_block));/*Marktheblockasbeingavailable*/mcb->is_available=1;/*That'sIt!We'redone.*/return;}void*mymalloc(longnumbytes){/*Holdswhereweareloo
8、kinginmemory*/void*current_location;/*Thisisthesameascurrent_location,butcasttoa*memory_control_block*/structmem_control_block*current_location_mcb;/*Thisisthememorylocationwewillreturn.Itwill*besetto0untilwefindsomethingsuitable
此文档下载收益归作者所有