2

I have create my own malloc function and it works properly. but I want to create another malloc using only array without struct. Is that possible to create without struct? This is my code.

#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");  
  }  

} 
Mohan
  • 1,871
  • 21
  • 34
Isuru Sandamal
  • 426
  • 1
  • 5
  • 10

1 Answers1

1

Roughly speaking, the basic mechanism to use would be the same. In MyMalloc, allocate 2*sizeof(int) space more, store the content of a chunk there and return the address behind the 2*sizeof(int). On deallocation, do the same process in reverse - subtract 2*sizeof(int) from the argument to access the content of which was stored in chunk before.

Codor
  • 17,447
  • 9
  • 29
  • 56