I am working on a program where a block of memory is allocated using malloc and pointers are used to add information to the block of memory. I am using an array of pointers since the number of pointers is dependent on the size of the block but I am running into some issues whenever I'm adding the information to the block. I had to shorten my code but basically this is what it looks like
struct Header{
int free;
int size;
};
void* memory_allocator(int length){
void* memoryBlock = malloc(length);
//assuming that length is a multiple of 2
int index = log2(length);
Header** freeList = (Header**)malloc(sizeof(Header)*(index+1));
freeList[index] = (Header*) memoryBlock;
freeList[index]->size = length;
freeList[index]->free = 1;
//Divide the memory block into chunks... This is where the problem happens
for(int j=1; j <= index; j++){
length = length/2;
freeList[index-j] = (Header*)(((char*)freeList[index])+length);
freeList[index-j]->size = length;
freeList[index-j]->free = 1;
}
}
My problem starts to happen at the for loop; it works fine at the first iteration but whenever it gets to the second it shoots a segmentation fault. The number I have been using to test this is 512 if it helps. Anybody can point out what I'm doing wrong please?