Reputation: 21
I am getting a segmentation fault when trying to run my program. After using valgrind these were my errors:
==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
this is the loop which my problem definitely exists, but I cannot find where:
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);
}
}
}
And this is an example of a text file I will be reading in:
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
Upvotes: 1
Views: 3560
Reputation: 53366
strtok()
can return NULL
so check value of token
before using it.
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);
}
}
Upvotes: 2
Reputation: 70971
strtok()
could very well return NULL
, which is not a good idea to pass to atoi()
.
Upvotes: 2