0

I'm doing pset5 and I'm currently implementing the load function.

bool load(const char* dictionary)
    {

    typedef struct node{

     struct node* next;
     char word[46];

    }node;

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

    node* letters[26];

    //Make all the next pointers NULL
    for(int j=0;j<26;j++){
     letters[j]->next = NULL;
    }

    //Check if file could be opened
    if(dic == NULL){

      printf("File not found, I repeat File not found");
      return false;

    }

    for(int i = 0;!feof;i++){

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

      //get the word and store it in the node
      fscanf(dic,"%s",new_node->word);

      //first time
      if(letters[hashy(new_node->word)]->next == NULL){

        //letters[hashy(new_node->word)]->word = new_node->word;

        strcpy(letters[hashy(new_node->word)]->word,new_node->word);

        letters[hashy(new_node->word)]->next = new_node;

      }else{

        node* crawler = letters[hashy(new_node->word)]->next;

        while(!(crawler->next == NULL)){

         crawler = crawler->next;

        }

        crawler->next = new_node;

      }

    }

    fclose(dic);

    return false;
}

This is my load function, I get a segfault when I run speller.c.

Here's what gdb's showing:-

(gdb) n
45      bool loaded = load(dictionary);
(gdb) step
load (dictionary=0xbffff294 "largedic") at dictionary.c:50
50      FILE* dic = fopen(dictionary,"r");
(gdb) n
55      for(int j=0;j<26;j++){
(gdb) n
56       letters[j]->next = NULL;
(gdb) n

Program received signal SIGSEGV, Segmentation fault.
0x08049012 in load (dictionary=0xbffff294 "largedic") at dictionary.c:56
56       letters[j]->next = NULL;
(gdb) n

I copied the large dictionary to the folder and renamed it largedic.

1

You created letters[26], an array of pointers to nodes. However you have not allocated any memory (malloc, calloc) for the array elements to point at. The for loop that follows then tries to assign NULL to an element in a nonexistent element with letters[j]->next = NULL; This causes the seg fault.

You can letters[j] = NULL; if you want to initialize it, or you can first malloc memory to letters[j] and then assign NULL to the next subelement. I'll leave it to you to sort out your program logic and your needs.

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

1
  • Oh right, thanks! – Jedi18 Oct 20 '15 at 6:21

You must log in to answer this question.

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