2015-11-05 125 views
2

我已经创建了我自己的malloc函数,它工作正常。但我想创建另一个malloc只使用阵列没有struct。有没有可能创建struct?这是我的代码。在c中创建自己的malloc函数

#include <stdio.h> 
char memory[20000]; 
int freeMem=20000; 

typedef struct{ 
    int start; 
    int end;  
}chunk; 

void *MyMalloc(int size){ 
    printf("\nMemory Size= %d ",size); 

    if(size==0){ 
    printf("0 means no memory\n"); 
    return 0; 
    } 

    int memsize=20000; 
    chunk *p=(chunk *)&memory[0]; 
    if(freeMem >= size+sizeof(chunk)){ 
    while(p<(chunk *)&memory[19999]){  
     if(p->start==0){ 
     if(p->end !=0){ 
      if(size+sizeof(chunk)< (p->end - (int)p)){ 
      p->start=(int)p+8; 
      p->end=(int)p+8+size; 
      freeMem = freeMem-(size+8); 
      printf("free Mem : %d\n",freeMem); 
      return (int *)p->start; 
      } 
      else{ 
      p=(chunk *)p->end; 
      continue; 
      } 
     } 
     else{ 
      p->start=(int)p+8; 
      p->end=(int)p+8+size; 
      freeMem = freeMem-(size+8); 
      printf("free Mem : %d\n",freeMem); 
      return (int *)p->start; 
     } 
     } 

     p = (chunk *)p->end; 
    } 
    } 
    else{ 
    printf("no space...!\n"); 
    return 0; 
    } 
} 
void MyFree(void * p){ 
    chunk *ptr = (chunk *)p; 
    ptr--; 
    freeMem=freeMem+(ptr->end - ptr->start)+sizeof(chunk); 
    if(ptr->start != 0){ 
    printf("\nfreed Memory : %d\t",ptr->end - ptr->start); 

    ptr->start = 0; 
    } 
    else{ 
    printf("\nno Such memory allocated!!!!!\n"); 
    } 

} 

回答

1

粗略地说,使用的基本机制是相同的。在MyMalloc中,更多地分配2*sizeof(int)空间,在那里存储chunk的内容并返回2*sizeof(int)后面的地址。取消分配时,请反过来执行相同的过程 - 从参数中减去2*sizeof(int)以访问之前存储在chunk中的内容。