Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working on a pset and I am having an error message: Looks like you're trying to use a variable that might not have a value? It says that cursor has not been initialised.I bolded the row where the error comes from.

I heed some help how to fix it, please.

for (int i = 0; i < N; i++)
    {
        node *cursor = table[i]; // place cursor to each bucket
        node *tmp = cursor; // create a tmp equal to cursor
        **while(cursor!= NULL)**
        {
            cursor = cursor->next; // move cursor to the next node
            free (tmp);
            tmp = cursor;
        }
        if (i == N-1)
        {
            return true;
        }

    }
    return false;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

Your loop is a bit awkward, and the function always returns true if N > 0. Yet your code seems fine and frees all the nodes. The memory leak is elsewhere: do the nodes have pointers to allocated memory (besides next)?

Here is a simpler version:

int free_table(node *table, int N) {
    for (int i = 0; i < N; i++) {
        node *cursor = table[i];       // use cursor to enumerate the bucket list
        table[i] = NULL;               // optional
        while (cursor != NULL) {
            node *next = cursor->next; // save the next pointer
            free(cursor);
            cursor = next;
        }
    }
    return N > 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...