I tried to create my own malloc function in C, using array as the memory i'll be working with. But when the remaining memory size surpasses a certain number of bits, the program crashes saying " Exception thrown: write access violation."
I divide the memory to a blocks. Each block will have a little metadata block that preserves the size of the block and whether is it free or taken (at the beginning, the entire memory array is one big block). Then my malloc finds the first memory block with sufficient size and uses it (or part of it).
The problem is: If i initialize an array of size 20000 bytes for example, my malloc will only work if the remaining free bytes in array would be 17708 or more.
#include <stdio.h>
char memory[20000];
struct block {
unsigned int size;
int free;
struct block* next;
};
struct block* freeList = (void*)memory;
void initialize() { /
freeList->size = 20000 - sizeof(struct block);
freeList->free = 1;
freeList->next = NULL;
}
void split(struct block* fitting_slot, unsigned int size) {
struct block* new = (void*)(fitting_slot + size + sizeof(struct block));
unsigned int temp = (fitting_slot->size) - size - sizeof(struct block);
printf("Remaining memory size is %d\n", temp);
new->size = temp; // this is where program crashes
new->free = 1;
new->next = fitting_slot->next;
fitting_slot->size = size;
fitting_slot->free = 0;
fitting_slot->next = new;
}
void* MyMalloc(unsigned int noOfBytes) {
struct block* curr;
void* result;
if (!(freeList->size)) {
initialize();
}
curr = freeList;
while ((((curr->size) < (noOfBytes + sizeof(struct block))) || ((curr->free) == 0)) && (curr->next != NULL)) {
curr = curr->next;
}
printf("From the free memory of size : %d\n", curr->size);
printf("We will occupy this size : %d\n", noOfBytes + sizeof(struct block));
if ((curr->size) == (noOfBytes + sizeof(struct block))) {
curr->free = 0;
result = (void*)(++curr);
printf("Exact fitting block allocated\n\n");
}
else if ((curr->size) > (noOfBytes + sizeof(struct block))) {
split(curr, noOfBytes);
result = (void*)(++curr);
printf("Fitting block allocated with a split\n\n");
}
else {
result = NULL;
printf("Sorry. No sufficient memory to allocate\n\n");
}
return result;
}
int main(){
unsigned int size = 2270 * sizeof(char);
char* k = (char)MyMalloc(size);
printf("Success\n");
}
If the number of "size" is 2269 or lower, program works correctly.
If the number of "size" in main is 2270 or higher, program crashes on the line
new->size = temp
in function split()
saying "Exception thrown: write access violation."