Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #define HEAP_SIZE 64
- #define FREE 0
- #define ALLOCATED 1
- void* my_malloc(size_t size);
- void my_free(void *p);
- char* header();
- char* footer();
- char* previous_header();
- char* previous_footer();
- char* next_header();
- char* next_footer();
- struct header {
- unsigned int length :29;
- unsigned int NOT_USED :2;
- unsigned int allocated :1;
- };
- struct footer {
- unsigned int length :29;
- unsigned int NOT_USED :2;
- unsigned int allocated :1;
- };
- static char* myHeap = FREE;
- void *my_malloc(size_t size)
- {
- if(size <=0)
- return NULL;
- if(myHeap){
- char* temp = myHeap;
- int allocated = 0;
- while(!allocated && temp!=(myHeap+(HEAP_SIZE-1))){
- if(temp)
- {
- struct header *hpTemp = temp;
- if(hpTemp->allocated==ALLOCATED)
- {
- int move = hpTemp->length;
- int i;
- for(i=0;i<move;i++)
- temp++;
- }
- }
- else
- {
- allocated = 1;
- }
- }
- errno=ENOMEM;
- printf("Unable to Allocate\n");
- return NULL;
- }
- else{
- myHeap = calloc(HEAP_SIZE,1);
- struct header *hp;
- hp=&myHeap[0];
- if(size>HEAP_SIZE){
- return NULL;
- }
- else
- {
- while(size%8!=0)
- {
- size++;
- }
- hp->length=(size+8);
- hp->allocated=ALLOCATED;
- struct footer *fp;
- fp = hp+(size+4);
- fp->length=(size+8);
- fp->allocated=ALLOCATED;
- return hp+4;
- }
- }
- return NULL;
- }
- void my_free(void *p)
- {
- struct header *temp = p-4;
- temp->allocated=FREE;
- if(temp-4->allocated==FREE&&temp!=myHeap)
- {
- int tempLength = temp->length;
- int leftTempLen = temp-4->length;
- temp-(8+leftTempLen)->length=(tempLength+leftTempLen+8);
- (footer)temp+tempLength->length=(tempLength+leftTempLen+8);
- temp+tempLength->allocated=FREE;
- temp-=(8+leftTempLen);
- }
- if(temp+4->allocated==FREE&&temp!=(myHeap+HEAP_SIZE))
- {
- int tempLength = temp->length;
- int rightTempLen = temp+(tempLength+4)->length;
- temp-(8+leftTempLen)->length=(tempLength+leftTempLen+8);
- (header)temp->length=(tempLength+leftTempLen+8);
- (footer)temp+(tempLength+rightTempLen+8)->allocated=FREE;
- }
- }
- char *header()
- {
- return NULL;
- }
- char *footer()
- {
- return NULL;
- }
- char *previous_header()
- {
- return NULL;
- }
- char *previous_footer()
- {
- return NULL;
- }
- char *next_header()
- {
- return NULL;
- }
- char *next_footer()
- {
- return NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement