在c中创建自己的malloc函数

时间:2015-11-05 11:34:12

标签: c

我已经创建了自己的malloc函数,但它运行正常。但我想仅使用不带malloc的数组创建另一个struct。是否可以在没有struct的情况下创建?这是我的代码。

#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 个答案:

答案 0 :(得分:1)

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