i want to implement a kind of malloc and free function for a course project , now i have done something but i dont know whats the problem with access violation in this line :
head->next = (struct block_meta *) allocate(sizeof(struct block_meta));
i'd be glad if someone can help me fix it or even if someone have any better idea for implementing this , ( cause obviously my implementation has a lot of problems) . thanks
#include<stdio.h>
#include <stdlib.h>
#define DATA_SEG_SIZE 65536
void* allocate(int size);
char data_seg[DATA_SEG_SIZE];
char* heap_top = data_seg;
char* stack_top = data_seg + DATA_SEG_SIZE - 1;
struct block_meta
{
unsigned char size;
struct block_meta *next;
void* block_ptr;
};
struct block_meta * first, *head;
void* search_for_free(int size)
{
head = first;
while ( head != NULL )
{
if ( head->size == size )
return head->block_ptr;
else
head = head->next;
}
return NULL;
}
void free_allocated(void* ptr, int size)
{
head = first;
if(head == NULL){
first = (struct block_meta *) allocate(sizeof(struct block_meta));
head = first;
}
else if(head->next == NULL){
head->next = (struct block_meta *) allocate(sizeof(struct block_meta));
head = head->next;
}
head->size = size;
head->block_ptr = ptr;
head->next = NULL;
}
void* allocate(int size)
{
if ( search_for_free(size) != NULL )
return search_for_free(size);
else if ( heap_top >= stack_top )
return NULL;
heap_top += size;
return (heap_top - size);
}
int main()
{
int *num;
int *p;
free_allocated(num, 8 * sizeof(char));
p = (int *) allocate(8 * sizeof(char));
free_allocated(p, 8 * sizeof(char));
p = (int*) allocate(50*sizeof(char));
return 0;
}