0

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;
         }

    }

}

1 Answer 1

1

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;
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

Right, that makes sense... I added indexes[i] = new set; at the top of the for loop and now it works. Thanks! Silly me, I didn't realize you need to initialize structs as well as classes, but since the array just has pointers, it makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.