Search code examples
clinked-listsegmentation-faultdefinition

C linked list define how to reimplement a list


Hi this is probably a stupid question to ask with a simple solution but I just can't find an answer in the internet.

So I was exercising for an exam and worked on an assignment. The program has the job to find out what the value in the center of a linked list is (if the length of the list is an odd number)

The structdef is:

typedef struct IntList IntList;
struct IntList {
    int value;
    IntList* next;
};

and my exact problem right now is that I get a segmentation fault when I try using:

list = list->next;

I want to go step by step in a loop to go to the wished list at the nth position (the center) of the linked list.

Someone knows how I have to rewrite this? If you need more Information to help just say so and I will explain more.

With that function I check the length of the list and in my other function I have a loop which only goes to the mid of the length.

int length_list(IntList* list) {
    int n = 0;
    for(IntList* node = list; node != NULL; node = node->next) n++;
    return n;
}

Solution

  • After this loop ends for(IntList* node = list; node != NULL; node = node->next) n++; you surely have node==NULL.
    That is not immediatly a problem.
    But depending on what you do with the value of n which you return you might have an off-by-one problem. E.g. in a list with exactly one entry (1 is odd after all), the attempt to use a value which is 1 too high could result in an attempt to access a non-existing node.

    Because of this I suspect that your problem might be solved by changing the loop to for(IntList* node = list; node->next != NULL; node = node->next) n++;, so that it ends on the last existing node, instead of behind. The return value will be lower, whatever you do with it will be "more-careful".

    That or try something similar with the small code fragment you show and ask about, list = list->next; only do that if the next is not NULL, not if only list is not NULL.