0

This is my code for load and valgrind points at line 127 as the reason for the seg. falut. Please, can someone point out to me why. Thanks.`/** *Loads dictionary into memory. Returns true if successful else false **/ void initialize(node* currentNode) { currentNode ->is_word = false; for(int k = 0; k < 27; k++) { currentNode ->children[k] = NULL; } }

bool load(const char dictionary) {
root = NULL; node
newNode = NULL; //point root to the travasal node: currentNode

      //create root node
    root = calloc (1, sizeof(node));
    currentNode = root; 

//open dictionary file & check if it's null 
inptr = fopen (dictionary, "r");

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

for (letter = fgetc(inptr); letter != EOF; letter = fgetc(inptr))
{
    if (isalpha (letter))
    {
        tolower(letter);
        indes = (letter - 'a');
    }

    if (letter == '\'')
    {
        indes = 26;
    }

    currentNode = currentNode -> children[indes];

    //if currentNode is null, malloc newnode
    if (currentNode -> children[indes] == NULL)
    {
        newNode = calloc (1, sizeof(node));
        currentNode = newNode;
    }

    currentNode = currentNode -> children[indes];

    if (currentNode -> is_word == true && letter == '\n')
    {
        word_count++;
    }

    currentNode = root;
}
    fclose(inptr);
        `

1 Answer 1

0

The segmentation fault error is probably due to the part of your code corresponding to callocing new node for the letter if NULL.

Your code:

if (currentNode -> children[indes] == NULL)
{
    newNode = calloc (1, sizeof(node));
    currentNode = newNode;
}

currentNode = currentNode -> children[indes];

You should alter it to following lines of code:

if (currentNode -> children[indes] == NULL)
{
    newNode = calloc (1, sizeof(node));
    currentNode->children[indes] = newNode;
}

currentNode = currentNode -> children[indes];

This is probably the cause for segmentation fault.

4
  • Thanks, Vikrant, but that didn't help. I added some code and that problematic line came to line 127. After running valgrind again, it gave this report: Invalid read of size 8 ==23127== at 0x4013B3: load (dictionary.c:127) ==23127== by 0x40095D: main (speller.c:40) ==23127== Address 0x8 is not stack'd, malloc'd or (recently) free'd Apr 20, 2017 at 17:40
  • which line of code is line 127 exactly? Apr 21, 2017 at 3:25
  • if (currentNode -> to children[indes] == NULL; Apr 21, 2017 at 6:45
  • just before that if statement on line 127 you are setting currentnode to the array index of the children array without checking for NULL. You can remove that line of code. Apr 21, 2017 at 7:33

You must log in to answer this question.

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