C 不确定为什么if语句会导致segfault
在我的一个函数中有一个C 不确定为什么if语句会导致segfault,c,segmentation-fault,C,Segmentation Fault,在我的一个函数中有一个if语句,当我用gdb查询它时,它似乎返回了一个有效的结果,但它最终还是给了我一个segfault 以下是所讨论的功能: /* 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;
if
语句,当我用gdb
查询它时,它似乎返回了一个有效的结果,但它最终还是给了我一个segfault
以下是所讨论的功能:
/* 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;
}
这里是我运行它的地方:
/* 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);
}
以下是我从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
正如您在上面所看到的,当我打印if
条件时,它返回true
很好,但是我在那一行(27)上得到了一个分段错误。我错过了什么
int read_file(FILE *in, T_node *root, int *max_len)
max_len
是一个指针
max_len = 0;
此行使max\u len
成为空指针
*max_len = len;
在这里,您尝试取消对空指针的引用
*max_len = len;
将max_len
的初始化更改为
*max_len = 0;
max_len
是一个指针
max_len = 0;
此行使max\u len
成为空指针
*max_len = len;
在这里,您尝试取消对空指针的引用
*max_len = len;
将max_len
的初始化更改为
*max_len = 0;
max_len=0代码>应为*max\u len=0
您得到一个segfault,因为您正在将max_len
更改为空指针,然后尝试取消引用它,这是未定义的行为。@Barmar谢谢,这就解决了它!但我不明白当我在gdb中执行“p*max_len”时,为什么它没有像通常那样给我无法访问内存位置消息?max_len=0代码>应为*max\u len=0
您得到一个segfault,因为您正在将max_len
更改为空指针,然后尝试取消引用它,这是未定义的行为。@Barmar谢谢,这就解决了它!但我不明白当我在gdb中执行“p*max_len”时,为什么它没有像通常那样给我无法访问内存位置消息?