0

I'm trying to use a trie structure to implement the load function in speller. I get a segmentation fault with the large dictionary, but not the small one. Text file size does not seem to matter, (I have not implemented check or unload yet). I've looked over some of the other questions asked about this issue, but none of the answers seem to apply to mine. Here is my code. It fails on else if (trav->children[asc] == NULL) during the large dictionary load, but I'm not sure why.

Here's the code in question:

bool load(const char *dictionary)
    {
    // make space for root

    root = malloc(sizeof(node));

    //traversal pointer
    node *trav = root;

    //integer for ascii conversion
    int asc = 0;

    //open dictionary
    FILE *dict = fopen(dictionary, "r");
    if (dict == NULL)
    {
        fprintf(stderr, "Dictionary %s\n is NULL\n", dictionary);
        return false;
    }

    for(int a = fgetc(dict); a != EOF; a = fgetc(dict))
    {
        asc = (int)a % 97;
        // if newline char, then set is_word to true, start over at root for next word
        if(asc == 10)
        {
            trav->is_word = true;
            trav = root;
        }
        // if the pointer is not pointing to anything (other than NULL), point to appropriate child[index]
        else if(trav->children[asc] == NULL)
        {
            // create a new node, then point to that node...
            trav->children[asc] = malloc(sizeof(node));
            trav = trav->children[asc];
        }
        // if an apostrophe, put at end of node array
    else if(asc == 39)
        {
            trav = trav->children[26];
        }
        else
        {
            trav = trav->children[asc];
        }
    }
    return true;
}
0

I see several flaws in the code. First, consider the following code:

for(int a = fgetc(dict); a != EOF; a = fgetc(dict))
{
    asc = (int)a % 97;
    // if newline char, then set is_word to true, start over at root for next word
    if(asc == 10)

What happens if the letter being processed is k? asc = 10. Both k and newline are being processed by this code.

Next, when processing an apostrophe, what happens when ->next == NULL? How is new memory allocated?

There may be other issues, but a rethink on some of this is necessary and may add or remove further issues.

You might think about a way to have both letters and asterisks processed by the same code to allocate memory and/or step to the next node rather than having the same code duplicated.

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

1
  • Thank you for pointing all those issues out! I set asc = 26 if it was an apostrophe and changed my newline check if statement to check for the actual newline character with if(a == '\n') I really appreciate the help! – brand n00bian Nov 23 '17 at 1:51

You must log in to answer this question.

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