0

以前にfindVertexNumberという別のプログラムで使用した関数があります。

私の新しいプログラムではうまくいきません。

おそらく私はエラーを見つけるにはあまりにも長い間コードを見つめてきましたが、2つのプログラムを比較すると、実装は同じように見えます。

うまくいけば、誰かが私のエラーを見つけることができます。

#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 ***
4

1 に答える 1

1

fclose(fp)を2回見ました。1つはmain()にあり、もう1つはfindVertexNumber()にあります

于 2012-10-03T02:44:57.737 に答える