user2180680
user2180680

Reputation: 229

Segmentation fault error in adjecency list function

I'm trying to write a function that does some calculations with a graph that is represented by a adjacency list, but I'm getting a segmentation fault error that I just don't get. Basically I'm first "removing" a node and then re-inserting it again. Here is my code:

int AdjList::bruteForce (node** list) {
    int pointerIndex;
    node* help;
    node* help2;

    for (int i=0; i<boundary; i++) {
        huidigScore = 0;
        help2 = list[i];
        help = help2;
        help2 = help2->next;
        while (help2->next != NULL) {
            help->next = help2->next;
            help2->next = NULL;
            pointerIndex = help2->number;

            help2->next = help->next;
            help->next = help2;
            help2 = help2->next;

        }   
    }
}

and the list initialization:

node** list;
node* help;
node* help2;
list = new node*[boundary];
for (int i=0; i<boundary; i++) {
    list[i] = new node;
    help = list[i];
    help->next = NULL;
    help->number = 0;
}

Thanks in advance.

Upvotes: 0

Views: 65

Answers (1)

alexrider
alexrider

Reputation: 4463

In your initialization help->next is always set to null, thus when it comes to

help2 = help2->next;
while (help2->next != NULL) {

help 2 is NULL and attempt to access help2->next in while loop leads to segfault.
EDIT
Same thing happens on last iteration of for loop, when i will be equal to boundary-1, help2 will hold pointer to the last value in list, with help2->next being NULL and everything will go by the previously described scenario. Thru I'm guessing here again about last entry in list having next set to NULL.

Upvotes: 2

Related Questions