0

When I try to run my program, a segmentation fault results. I don't think I am accessing memory that I am not supposed to. Is my code fundamentally wrong?

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

    if(fp == NULL)
    {
        printf("Could not open the dictionary\n");
        return false;
    }

    for(int i = 0; i < 26; i++)
    {
        hashtable[i] = NULL;
    }

    int hashvalue;

    while(!feof(fp))
    {
        node* new_node = malloc(sizeof(node));
        fscanf(fp, "%s", new_node->word);
        hashvalue = hash(new_node->word);

        //if the list is empty
        if(hashtable[hashvalue] == NULL)
        {
            new_node->next = NULL;
            hashtable[hashvalue] = new_node;
            wordcount++;
        }

        //in between
        else
        {
            node* cursor = hashtable[hashvalue];

            while(cursor != NULL)
            {
                if((strcmp((new_node->word), (cursor->word)) > 0 && strcmp((new_node->word), ((cursor->next)->word)) < 0) || (strcmp((new_node->word), (cursor->word)) == 0))
                {
                    new_node = cursor->next;
                    cursor->next = new_node;
                    break;
                }
                cursor = cursor->next;
                wordcount++;
            }

            //reach the end
            if(cursor == NULL)
            {
                new_node->next = NULL;
                cursor->next = new_node;
                wordcount++;
            }
        }
    }

    return true;
}
0

Unless you've done it outside load() (which we cannot see here), you don't seem to have declared hashtable, which would result in a segfault when you try to initialize it.

2
  • I have declared an hashtable globally.... Valgrind shows the problem is in this line..which i don't know why.. if((strcmp((new_node->word), (cursor->word)) > 0 && strcmp((new_node->word), ((cursor->next)->word)) < 0) || (strcmp((new_node->word), (cursor->word)) == 0)) – Yat Long Lo Dec 4 '14 at 3:23
  • I can't spot your problem (sorry =P). Perhaps you could try splitting all those pointer-to-structure access in different lines, to try and determine precisely the one that's generating the segfault. And that could make a better start for a bug-hunt ;) – abelinux Dec 4 '14 at 17:08
0

Your segmentation fault might be due to a problem I was having as well, you can see my question and answer here:

Pset6 "Size" giving the wrong output

if fscanf scans a NULL value and you are using a char * instead of a char for your "word" data, your load will seg fault at the end of the file. You can check this using "printf" or "fprintf" after fscanf, so you can see when you are seg faulting.

You must log in to answer this question.

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