简体   繁体   中英

Unsure why if statement causes segfault

I have this if statement in one of my functions that seems to return a valid result when I query it with gdb , but it still ends up giving me a segfault .

Here is the function in question:

/* reads the file and adds each word to the trie
   returns the number of unique words in the file */
int read_file(FILE *in, T_node *root, int *max_len)
{
   char *word = NULL;
   int num_unique = 0;
   int len;
   max_len = 0;

   if(root == NULL)
   {
      perror("Bad root");
      exit(3);
   }

   while ((word = read_long_word(in)) != NULL)
   {
      len = strlen(word);
      /************ segfault here ***********/
      if (len > *max_len)
      {
         *max_len = len;
      }
      num_unique += add_word(root, word);
   }

   return num_unique;
}

Here is where I am running it from:

/* tests file with some repeated words */
void test_read_file2(void)
{
   FILE *in = fopen("repeated.txt", "r");
   T_node *root = create_T_node();
   int max_len = 0;
   /****** segfault caused by this call *****/
   checkit_int(read_file(in, root, &max_len), 8);
   checkit_int(max_len, 19);
   free_trie(root);
   fclose(in);
}

And here is what I get from gdb :

27            if (len > *max_len)
(gdb) p len
$4 = 5
(gdb) p *max_len
$5 = 0
(gdb) s

Program received signal SIGSEGV, Segmentation fault.
0x0000000000402035 in read_file (in=0x605010, root=0x605250, 
    max_len=0x7fffffffe0dc) at fw.c:27
27            if (len > *max_len)
(gdb) p *max_len
$6 = 0
(gdb) p len > *max_len
$7 = 1

As you can see just above, when I print the if condition it returns true just fine, but I get a segmentation fault on that line (27) anyway. What am I missing?

int read_file(FILE *in, T_node *root, int *max_len)

max_len is a pointer

max_len = 0;

This line makes max_len a null pointer.

*max_len = len;

Here you try to dereference a null pointer.

Change the iniitialization of max_len to

*max_len = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM