0

I need some guidance on where I'm going wrong here.

GDB runs fine until I try to access the "next" property of a node to see if it's NULL.

Am I just confusing how the node structure works? My interpretation is that because I can pass a word into the node through the scanf call then so too must the "next" element contain something (presumably NULL).

bool load(const char* dictionary)
{
    FILE *dict = fopen(dictionary,"r");
    if (dict == NULL)
    {
       printf("Could not open %s.\n", dictionary);
       return 1;
    }

    node *new_node = (node *) malloc(sizeof(node));
    if (new_node == NULL) // checking for insufficient memory
    {
        return false;  
    }

    int index;

    // for each word in dict
    while (fscanf(dict,"%s",new_node->word) == 1)
    {
        index = hash(new_node->word);

        //first insertion in index
        if (h_table[index]->next == NULL) // *** KEEPS CRASHING HERE ***
        {
            new_node->next = h_table[index]->next;
            h_table[index] = new_node;
            break;
        }

Here are my GDB print statements which produced some strange output

after the scanf call in the while statement, which supposedly passed the first word to new_node's word element, I printed to see what was going on

(gdb) p new_node->word
Cannot access memory at address 0x0

Then I tried just this

(gdb) p new_node
$2 = (node *) 0x0

Any help would be much appreciated.

0

I'm not seeing you trying to access next with gdb. Rather, you're trying to print the value of new_node->word which appears to be not accessible because new_node itself appears to be equal to NULL (i.e., address 0x0).

Also, you shouldn't rely on a value of a variable without initializing it first.

It keeps crashes here

if (h_table[index]->next == NULL)
{
    // some code
}

because you've never allocated memory for h_table[index] before neither did you set it to point to an already allocated location in memory. However, you're still trying to access h_table[index]->next which doesn't exist yet.

I advise you to take a look at section 7. The process of inserting a node into a linked-list is explained and demonstrated there.

2
  • Hi Kareem, thank you for your response. One thing I just realized too was that when I step through this part of the code: node *new_node = (node *) malloc(sizeof(node)); and then print the value of *new_node I get empty values for word and *next but then when i go through: while (fscanf(dict,"%s",new_node->word) == 1) and print again *new_node I get the following: cannot access memory address at 0x0
    – gedm
    Oct 2 '14 at 0:04
  • @gedm could you please update your question showing what gdb tells you when you malloc memory for new_node, printing its value then printing the value of new_node->word?
    – kzidane
    Oct 2 '14 at 1:29

You must log in to answer this question.

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