I have a function which I’ve used previously in another program called findVertexNumber.
It will not work for me in my new program.
Perhaps I’ve been staring at code for too long to spot the error, but it seems identical in implementation to me when I compare the two programs.
Hopefully someone can spot my error….
#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
}
The file its reading is a text file, maybe there’s something wrong in the format of it?
Here it is:
1 3
1 4
2 3
2 4
5 7
5 8
6 8
6 9
The error comes from the while statement as far as I can tell through comment debugging and is :
*** glibc detected *** ./a.out: double free or corruption (top): 0x0000000000ee3010 ***
I saw fclose(fp) twice. One in main(), the other in findVertexNumber()