Search code examples
c++pointersstructdynamic-arrays

Dynamic array of pointers to struct throws SIGSEGV on member variable assignment


I'm quite sure this a simple issue, but I am trying to create a data structure that implements a dynamic array of structs.

Each struct will implement a linked list.

So I think that I want an array of pointers, which will point to the head of each list. For some reason, assigning method variables gives me a seg fault. I would love a little explanation of what I am doing wrong if you could. THANKS!

Oh, also, all of this is inside a class called Cache, so that is why there are some variables that don't appear to be defined, but I assure you they are. The program seg faults on indexes[i]->next = NULL; and the similar lines below that one.

        typedef struct setNode {
    char valid, dirty;
    unsigned int tag;
    setNode *next;
    Cache *nextCache;

} set;
    set **indexes;

    arrayLength = cache_size / block_size;

    indexes = new setNode *[arrayLength];

    set *temp;

    //Step through the array. The array is full of pointers to "Dummy Nodes"
    for (size_t i = 0; i < arrayLength; i++) {
        indexes[i]->next = NULL;
        indexes[i]->valid = 0;
        indexes[i]->dirty = 0;
        indexes[i]->tag = 0;
        //create empty linked list for each tag spot (One for direct mapped. etc...)

         for(size_t i = 0; i < associativity; i++)
         {
         temp = indexes[i];
         temp->next = new setNode;
         temp = temp->next;
         temp->next = NULL;
         temp->valid = 0;
         temp->dirty = 0;
         temp->tag = 0;
         }

    }

}

Solution

  • indexes is an array of pointers to set objects, but they are uninitialized. They don't point to actual set objects, but merely to random memory locations. Trying to write to random memory is the very essence of the segmentation violation.

    Before using your pointers, you need to allocate set objects and make the pointers point to them -- i.e.,

    for (size_t i = 0; i < arrayLength; i++) {
        indexes[i] = new set;
        indexes[i]->next = NULL;
        indexes[i]->valid = 0;
        ...