0

When I use this using the small dictionary, it works but when I use the large dictionary I get a Segmentation Fault.. What could it possibly be due to?

Here is my code:

bool load(const char* dictionary)

{

FILE* fp = fopen(dictionary, "r");

if (fp == NULL)

{

    printf("Couldn't open %s.\n", dictionary);

    return false;  

}


while(!feof(fp))

{

    node* new_node = malloc(sizeof(node));

    fscanf(fp,"%s",new_node->word);

    //printf("%s\n", new_node->word);

    int key = hash(new_node->word);

    if(hashtable[key] == NULL)

    {

        hashtable[key] = new_node;

        new_node->next = NULL;

    }

    else

    {

        new_node->next = hashtable[key];

        hashtable[key] = new_node;

    }

    num++;

}

fclose(fp);

return true;

}

The seg fault mostly lies in the else region..

My hash function is a simple one which returns the toupper(word[0]) -'A'.

Thanks in advance :)

1
  • When the small dictionary works and the large seg faults it generally indicates a memory leak. Run with the small dictionary under valgrind and it should lead you to where problems are. – DinoCoderSaurus Jun 24 '16 at 19:25
1

You have a logic structure issue in your load function. The logic of this code is to read a word, process it, and then to check for feof(). The seg fault hits when load tries to process a word beyond the end of the file.

You need to check for EOF as part of the read or immediately after. Two common approaches are to put an EOF test with a break statement immediately after the read statement, or to incorporate the fscanf into the while setup, using the return value of the fscanf to detect the EOF condition.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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