Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

Memory leak while freeing a hash table C

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...