0

I looked through my load function with debug50 and realised that each time the loop is iterated, the pointer temp always gets assigned the same value despite freeing it, how do Igo about resolving this?

bool load(const char *dictionary)
{    FILE *dict = fopen(dictionary, "r");
    if (dict == NULL)
    {
        return false;
    }

    for (int j = 0; j < N; j++)
    {
        table[j] = NULL;
    }

    char string[46];

    while (fscanf(dict, "%s", string) != EOF)
    {
        node *temp = malloc(sizeof(node));
        if (temp == NULL)
        {
            return false;
        }
        strcpy(temp->word, string);
        temp->next = NULL;
        unsigned int bucket_number = hash(string);

        if (table[bucket_number] == NULL)
        {
            table[bucket_number] = malloc(sizeof(node));
            table[bucket_number] = temp;
        }
        else
        {
            temp->next = table[bucket_number];
            table[bucket_number] = temp;
        }
        word_count++;
        free(temp);
        memset(string, 0, 45);
    }
    fclose(dict);
    return true;
}
5
  • Take out free(temp). – user3671 Jun 10 '20 at 12:00
  • @user3671 whats the rationale behind it? – tangolin Jun 10 '20 at 12:16
  • I see DinoCoderSaurus has already explained. Do please accept his answer as correct for the benefit of later readers. – user3671 Jun 10 '20 at 16:59
  • Are you allocating memory in your if statement to create a node to become the bucket number if the bucket number is NULL after being hashed? Could you explain the if statement too? I get lost trying to follow. – ayeeitsalpha Jul 5 '20 at 23:01
  • @ayeeitsalpha yep so if the nth array is empty, n being the bucket number, im allocating memory the size of a node, and it will take on the same value as temp – tangolin Jul 20 '20 at 2:17
0

pointer temp always gets assigned the same value despite freeing it

Acutally, it's not despite it's because of! The free releases the memory and makes it available again. It also "wipes out" the node that has just been built. The program, therefore, will have an empty linked list at the end of load.

2
  • I see! In that case, am I right to say that essentially I need not free(temp) because the memory is now stored with certain data and temp as a pointer is just a certain local variable? – tangolin Jun 10 '20 at 14:02
  • Yes, i'd agree that is right. – DinoCoderSaurus Jun 10 '20 at 14:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .