Home > Mobile >  Keep getting dereferencing NULL pointer error when using linked list
Keep getting dereferencing NULL pointer error when using linked list

Time:10-16

I am trying to find a string in my linked list(Its location is determined by an integer starting at 1) and move it to the front of the list. I have not put in the move to the front of the list code yet, as I have not been able to deal with this error.

typedef struct node NODE;
struct node
{
    char word[WORDSIZE];    
    struct node* next;      
};

NODE* start;


int add_to_list(NODE** start, char data[])
{

    NODE* new;
    NODE* curr;

    curr = *start;

    if ((new = malloc(sizeof(NODE))) == NULL)
        return -1;

    strcpy_s(new->word, WORDSIZE, data);
    new->next = *start;
    *start = new;

    return 0;
} 

void FindPrintMove(NODE* start, int index) {
    int size = 0;
    NODE* cur = start;
    while (cur != NULL) {
        size  ;
        cur = cur->next;
    }
    cur = start;
    int i = 1;
    while (i < (size - index)) {
        cur = cur->next;
    
    }
    printf("%s", cur->word);
}

I feel like I could use a doubly linked list or add to the end instead of the start but i dont think that would solve this issue

CodePudding user response:

It is unclear what is the purpose of this while loop

while (i < (size - index)) {
    cur = cur->next;

}

but within it the variable i is not being changed. So you have an infinite loop that will be broken when the tail of the list will be achieved and a null pointer will be dereferenced.

Pay attention to that positions in the list should start from 0.

CodePudding user response:

void FindPrintMove(NODE* start, int index) {
    int size = 0;
    int i = 0;
    NODE* cur = start;

    while (size < index) {
        cur = cur->next;
        size  ;
        //printf("%s ", cur->word);
    }
    printf("%d", size);
    cur = start;
    while (i < size) {
        cur = cur->next;
    }
    printf("%s", cur->word);
 }
  • Related