1

When I run my load function with ./speller text, it reported segmentation fault. When I use valgrind to check, it told me that the problem in the two line:

char new_word[LENGTH + 1]; while(fgets(new_word, LENGTH + 1, fp) != NULL)

and large number of memory is allocated with 0 free. Can anyone point out the problem? Thanks in advance

This is what my entire code looks like:

 bool load(const char* dictionary)
{    
     // Open the dictionary file 
     FILE* fp = fopen(dictionary, "r");

     if (fp == NULL)
         return 1;

    //create a hash table and set heads to null
    typedef struct node
    {
        char word[LENGTH + 1];
        struct node* next;   
    }
    node;

    node* table[CAPACITY]
    for (int i = 0; i < CAPACITY, i++)
        table[i] = NULL;

    //read through the dictionary
    char* new_word[LENGTH + 1];
    while (fgets(new_word, LENGTH + 1, fp) != NULL)
    {
        node* new_node = malloc(sizeof(node));
        if (new_node == NULL)
            return 2;

        new_node->word = new_word;

        //hash the new word
        int hash = hash_fun(new_word);
        //insert the new word to the local linked list
        if (table[hash] == NULL)
        {
            new_node -> table[hash];
            table_hash = new_node;
        }

        node* cursor = table[hash];        
        while (cursor != NULL)
        {
           node* pre = cursor;
           cursor = cursor->next;

        pre->next = new_node;
        new_node->next = NULL;

        return true;
    }
}
1
  • I changed fgets to fscanf. Now there is no seg fault, but terminal shows "could not open text"
    – eifphysics
    Commented Feb 19, 2015 at 23:52

1 Answer 1

1

fgets() will get a string including '\n' character, so you have to call it with (LENGTH + 2) parameter. And you have to have a storage for this amount of chars. And don't forget to remove '\n' from the end of string.

You must log in to answer this question.

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