#include<stdio.h> #include<stdlib.h> #define TRUE 1 #define FALSE 0 #define MAX 1000 typedef struct st_tag { void *baseAddr; int size; int free_flag; struct st_tag *next; }node_type; void initialize_getmemory(void); void print_mem_info(void); void *mymalloc(int size); void myfree(void *xx); node_type *hptr; void main() { int *iptr; initialize_getmemory(); print_mem_info(); iptr=(int *)mymalloc(10*sizeof(int)); iptr[0]=10; iptr[1]=20; printf("The iptr[0]= %d addr = %u\n",iptr[0] , &iptr[0]); printf("The iptr[1]= %d addr = %u\n",iptr[1] , &iptr[1]); print_mem_info(); printf("Try to free memory\n"); myfree(iptr); print_mem_info(); } void *mymalloc(int size) { node_type *ptr=hptr; node_type *temp; int delta; while(ptr) { if(ptr->free_flag == TRUE && ptr->size >=size) { break; } ptr=ptr->next; } if(ptr) { temp=(node_type *)malloc(sizeof(node_type)); temp->next=ptr->next; ptr->next=temp; delta = (int)ptr->baseAddr - (int)hptr->baseAddr; temp->baseAddr=(void *)((int)ptr->baseAddr + MAX - (delta + size) ); temp->free_flag = FALSE; temp->size = size; ptr->size = ptr->size - size; return (void *)temp->baseAddr; } else { return (void *)NULL; } } void myfree(void *xx) { node_type *ptr; node_type *temp; int success=FALSE; ptr=hptr; if(ptr->baseAddr==xx) { success=TRUE; if(ptr->next == NULL || ptr->next->free_flag == FALSE) { ptr->free_flag = TRUE; } else { ptr->free_flag = TRUE; ptr->size = ptr->size + ptr->next->size; ptr = ptr->next; hptr->next = ptr->next; free(ptr); } } else { while(ptr->next) { if(ptr->next->baseAddr == xx) { success=TRUE; if(ptr->free_flag == FALSE) { if(ptr->next->next == NULL || ptr->next->next->free_flag == FALSE) { ptr->next->free_flag = TRUE; } else { ptr=ptr->next; ptr->free_flag = TRUE; ptr->size = ptr->size + ptr->next->size; temp=ptr->next; ptr->next = temp->next; free(temp); } } else { if(ptr->next->next == NULL || ptr->next->next->free_flag == FALSE) { ptr->size = ptr->size + ptr->next->size; temp=ptr->next; ptr->next = temp->next; free(temp); } else { ptr->size = ptr->size + ptr->next->size + ptr->next->next->size; temp=ptr->next; ptr->next = temp->next->next; free(temp->next); free(temp); } } break; } ptr=ptr->next; } } if(success == FALSE) { printf("Unable to free the memory\n"); } } void initialize_getmemory(void) { node_type *head; head=(node_type *)malloc(sizeof(node_type)); head->baseAddr=(void *)malloc(MAX); head->size=1000; head->free_flag=TRUE; head->next=NULL; hptr=head; } void print_mem_info(void) { node_type *ptr=hptr; while(ptr) { printf("The base address is %u\n",ptr->baseAddr); printf("The size is %d\n",ptr->size); printf("The free_flag %d\n\n",ptr->free_flag); ptr=ptr->next; } }