我有一个我以前在另一个名为 findVertexNumber 的程序中使用过的函数。
它不适用于我的新程序。
也许我一直盯着代码太久没有发现错误,但是当我比较这两个程序时,它的实现对我来说似乎相同。
希望有人能发现我的错误....
#include <stdio.h>
#include <stdlib.h>
int findVertexNumber(FILE *fp);
int main(int argc, char *argv[])
{
if(argc != 2) //insure 2 arguments given, one for a.out and one for the test file
{
printf("Requires 2 arguemnts. Be sure to include test file location\n"); //result if request fails
return 0;
}
FILE *fp; //variable declartion
int numberVertices = 0;
int i, j;
fp = fopen(argv[1], "r"); //open the file provided
numberVertices = findVertexNumber(fp); //find the number of vertices in the graph
fclose(fp);
printf("Max vertex number is: %d\n", numberVertices);
}
int findVertexNumber(FILE *fp) //function finds the largest number in the file, assumed to be number of
{ //vertices
int max = 0;
int e1, e2;
while(fscanf(fp, "%d %d", &e1, &e2) != EOF) //continue to end of file
{
if(e1 > max) //check if e1 is greater than max
{
max = e1; //if true, update max
}
if(e2 > max) //check if e2 is greater than max
{
max = e2; //if true update max
}
}
fclose(fp); //close file
return max; //return max number, number of vertices
}
它读取的文件是一个文本文件,也许它的格式有问题?
这里是:
1 3
1 4
2 3
2 4
5 7
5 8
6 8
6 9
据我通过注释调试可以看出,该错误来自该while
语句,并且是:
*** glibc detected *** ./a.out: double free or corruption (top): 0x0000000000ee3010 ***