Friday, July 20, 2012

Malloc And Free Function Implementation In C

         Do you want to publish source codes in your blog or web site as follows.
                              Visit Source Code Formatter

 #include <stdio.h>    
     
 char memory[50000];  
 int freeMem=50000;  
   
 typedef struct{  
   int start;  
   int end;  
     
 }node;  
   
 void *NewMalloc(int size){  
   printf("\nRequested Memory= %d\t\t",size);  
   
   if(size==0){  
     printf("Can't allocate 0 size memory\n");  
     return 0;  
   }  
     
   int memsize=50000;  
   node *N=(node *)&memory[0];  
   if(freeMem >= size+sizeof(node)){  
     while(N<(node *)&memory[49999]){    
       if(N->start==0){  
         if(N->end !=0){  
           if(size+sizeof(node)< (N->end-(int)N)){  
             N->start=(int)N+8;  
             N->end=(int)N+8+size;  
             freeMem = freeMem-(size+8);  
             printf("free Mem : %d\n",freeMem);  
             return (int *)N->start;  
           }  
           else{  
             N=(node *)N->end;  
             continue;  
           }  
         }  
         else{  
           N->start=(int)N+8;  
           N->end=(int)N+8+size;  
           freeMem = freeMem-(size+8);  
           printf("free Mem : %d\n",freeMem);  
           return (int *)N->start;  
         }  
       }  
           
       N = (node *)N->end;  
     }  
   }  
   else{  
     printf("there is not enaugh space to allocate required memory\n");  
     return 0;  
   }  
 }  
 void NewFree(void * p){  
   node *ptr = (node *)p;  
   ptr--;  
    freeMem=freeMem+(ptr->end - ptr->start)+sizeof(node);  
      if(ptr->start != 0){  
     printf("\nfreed memory size : %d\t",ptr->end - ptr->start);  
        
        printf("Now available memory : %d ",freeMem);  
     ptr->start = 0;   
        printf("\nMemory Freed...\n");  
   }  
   else{  
     printf("\nThere is no such allocated memory for this address!!!!!\n");  
   }  
     
 }   
 int main(){  
   
   char *str;  
   str=NewMalloc(10000);  
   printf("address : %d\n",(int)str);    
   
   char *str1;  
   str1=NewMalloc(0);  
   printf("address : %d\n",(int)str1);    
   
   char *str2;  
   str2=NewMalloc(10000);  
   printf("address : %d\n",(int)str2);    
     
   char *str3;  
   str3=NewMalloc(10000);  
   printf("address : %d\n",(int)str3);    
   
   char *str4;  
   str4=NewMalloc(10000);  
   printf("address : %d\n",(int)str4);  
 NewFree(str2);  
   char *str5;  
   str5=NewMalloc(12000);  
   printf("address : %d\n",(int)str5);    
   return 0;  
 }  

1 comments:

  1. Malloc And Function Implementation In C >>>>> Download Now

    >>>>> Download Full

    Malloc And Function Implementation In C >>>>> Download LINK

    >>>>> Download Now

    Malloc And Function Implementation In C >>>>> Download Full

    >>>>> Download LINK 5h

    ReplyDelete