手动实现malloc函数(c语言)

用C语言实现一块内存的管理操作,包括申请、释放、替换等操作

#include 
#include 
#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;
}

参考:https://blog.csdn.net/wxx258369/article/details/78731964(有改动)

你可能感兴趣的:(手动实现malloc函数(c语言))