简体   繁体   中英

Segmentation Fault when using array of pointers

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?

The block you malloc is not initialized with NULL. You probably try to dereference an unititialized pointer.

Use calloc instead. The block will be initialized to NULL.

Header** freeList = calloc(index+1, sizeof(Header*));

You are also realocating the freelist for every block insertion. Is this really what you want ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM