0

I need some help in spotting where is the problem in my load and unload functions and if the logic is correct. Also, whenever I execute valgrind and its telling me: definitely lost: 8,013,040 bytes in 143,090 blocks. I triple checked both functions and still cannot find the leaks and why they are not running properly.

Code:

bool load(const char* dictionary)
{

    unsigned int hash_index=0;

    FILE *fp = fopen(dictionary, "r");
    if(fp == NULL)
    {
        fprintf(stderr, "Couldn't open %s",dictionary);
        return false;
    }

    //dictionary 


    while(true)
    {
        node *temp = malloc(sizeof(node));
        if (temp == NULL)
        {
            unload();
            fclose(fp);
            return false;
        }


        if(fscanf(fp , "%s", temp->word) == 1)   //storing word of dictionary in my new_node -> word
        {
            hash_index = hash(temp->word); 
            head = hashtable[hash_index];    //head always points to first element of linked list

            // adding word into linked list
            if(head == NULL || (strcmp(temp->word,head->word) < 0) )
            {
                temp->next = head;
                head = temp;
            }
            else
            {
                node *cur, *prev;
                for (cur = head, prev = NULL;
                     cur != NULL && (strcmp(cur->word, temp->word) < 0);  //if n is less than cur->value it breaks out of loop
                     prev = cur, cur = cur->next);

                temp->next = cur;
                prev->next = temp;
            }

            hash_num++;
        }
        else 
        {
            free(temp);   
            break;
        }
    }

    fclose(fp);
    return true;

}

bool unload(void)
{

    for(int i=0; i<SIZE; i++)
    {
        if(hashtable[i] != NULL)      //if hashtable isn't NULL (has nodes)
        {
            node *cursor = hashtable[i];        //cursor points at head of individual linked list
            while(cursor != NULL)       //free them
            {
                node *temp = cursor;
                cursor = cursor->next;
                free(temp);
            }
        }
    }

    return true;
}

I'd appreciate any guidance

  • Memory leaks is the only problem in your code, does it run correctly? – A.Emad Dec 27 '16 at 8:56
  • It doesn't run correctly, it failed all check50 points except the compile one – tadm123 Dec 27 '16 at 23:15
  • Where is the declaration of the hash variable, hast table variable...? – sp3 Jun 1 '17 at 0:07

You must log in to answer this question.

Browse other questions tagged .