0

I'm currently doing the load part of pset 5 and I ran into a problem I was not yet able to solve. This is my code:

bool load(const char* dictionary)
{
FILE* dic = fopen(dictionary, "r");
typedef struct node {
    bool is_word;
    struct node* children[27];
} node;

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


char* word = (char*) malloc(45);
int length = 0;
while (true){

    fscanf(dic, "%s", word);
    while (isalpha(word[length]) || word[length] == '\''){
        length++;
    }


    while (length > 0){
        node* newroot = root;
        for (int i = 0; i < length; i++){
            if (newroot->children[word[i]-'a'] == NULL){ // The error happens here
                newroot->children[word[i]-'a'] = (node*) malloc(sizeof(node*));
                newroot = newroot->children[word[i]-'a'];

            }
            else
            {
                newroot = newroot->children[word[i]-'a'];
            }

            if (i == length-1){
                newroot->is_word = true;
                length = 0;
            }
        }

    }
}    

return false;
}

I tried using GDB and it goes like this (word being read is 'cat') : When mallocing in the declaration of root, most of the root's children are null but some have a value, one of the children with value is at index 2 representing c (all of the c's children are of value NULL). Therefore during the first iteration of the for loop the else code block is executed and newroot is changed. During the second iteration the segmentation fault happens on the line with the comment. My guess is there is something wrong with how i try to malloc the null pointer but i honestly don't know. Thank you for every answer.

1

There are two major problems in the code. First, look at this:

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

The parameter for malloc is the size of the object that needs to be allocated. Unfortunately, by adding the asterisk in the sizeof() call, you are allocating just enough memory to store a pointer to a node, not an actual node, which is much larger. This error is repeated later. Instead, try this:

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

The second problem is that there is no code to check for the end of file condition on the dictionary file, so once you fix the seg fault, it's going to have an infinite loop.

There are other issues which I'll leave for you to sort out, but these are the big problems.

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

1
  • Thank you so much, there was no chance i would realize this. Apr 26 '16 at 18:20

You must log in to answer this question.

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