尝试运行程序时出现分段错误。使用valgrind后,这些是我的错误:
==32592== Invalid read of size 1
==32592== at 0x3753637172: ____strtol_l_internal (strtol_l.c:298)
==32592== by 0x3753633F1F: atoi (atoi.c:28)
==32592== by 0x400B12: main (in /some/directory)
==32592== Address 0x0 is not stack'd, malloc'd or (recently) free'd
这是我的问题肯定存在的循环,但我无法找到:
while( fgets(line, MAX_LEN, in) != NULL ) {
++linenum;
token = strtok(line, " \n");
if ( linenum == 1 ) {
n = atoi(token);
G = newGraph(n);
}else {
x = atoi(token);
token = strtok(NULL, " \n");
y = atoi(token);
if( x != 0 ) {
addArc(G, x, y);
}
}
}
这是我将要阅读的文本文件的示例:
9
1 2
2 1
2 3
3 5
5 4
4 3
5 6
6 8
7 6
8 7
8 9
1 3
1 4
1 5
1 6
1 7
1 8
1 9
2 4
2 5
2 6
2 7
2 8
2 9
3 6
3 7
3 8
3 9
4 6
4 7
4 8
4 9
5 7
5 8
5 9
6 9
7 9
9 9
0 0
答案 0 :(得分:2)
strtok()
很可能会返回NULL
,这不是传递给atoi()
的好主意。
答案 1 :(得分:2)
strtok()
可以返回NULL
,因此请在使用前检查token
的值。
token = strtok(line, " \n");
if(token != NULLL)
{
if ( linenum == 1 ) {
n = atoi(token);
G = newGraph(n);
}else {
x = atoi(token);
token = strtok(NULL, " \n");
if(token != NULL)
y = atoi(token);
if( x != 0 ) {
addArc(G, x, y);
}
}