I keep getting a segmentation fault on my load function when using the debugger. Specifically, the line with "if(table[num]->next != NULL)" is what is causing it. I need some help, please.

bool load(const char *dictionary)
    unsigned int num = 0;

    char buffer[LENGTH + 1];

   //Open dictionary file

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

   if(ptr == NULL)

       printf("Can't open dictionary");

       return false;

    //Read string from file one at a time
    while(fscanf(ptr,"%s",buffer) != EOF)
        //Create a new node for each word
        node* n =malloc(sizeof(node));

        if(n != NULL)
            n->next = NULL;
        //Hash word to obtain a hash value for each word
        num = hash(buffer);

        //Check to see if something already at location
        if(table[num]->next != NULL)

             n->next = table[num];
        //Insert node into hash table at that location
        table[num] = n;

        //keeps track of how many words in dictionary


    return false;

1 Answer 1


I see two problems here. First, table[] isn't initialized before being used. Second, looking specifically at your line of code, if table[num] doesn't exist (is NULL) or still contains garbage(not initialized), then table[num]->next doesn't exist, so it will throw a seg fault.

  • I didn't include it in my post but I did declare table with char table[46]. I wan't to add nodes to my hash table for each word. However, I'm confused how to do this when multiple words are grouped on one row of the hash table as a linked list.
    – Bob
    Jul 2, 2020 at 5:33
  • I'm going to guess that you actually did char * table[46];. That means these are all pointers. Creating a pointer array does NOT initialize the table. Every pointer will contain garbage data. You would also need to set all the elements to NULL (at the beginning of load). If you actually didn't use the asterisk, which makes it an array of pointers, how would you store the addresses of new nodes?
    – Cliff B
    Jul 2, 2020 at 6:08

You must log in to answer this question.

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