我之前在另一个程序中使用过一个名为 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 ***
最佳答案
我看到了 fclose(fp) 两次。一个在 main() 中,另一个在 findVertexNumber() 中
关于c - 功能不起作用,GDB 也没有发现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12701097/