-1

引数として2つのファイル(mat1.txtとmat2.txt)を使用して行列乗算プログラムを実装しようとしています。結果をファイルにロードすることにしましたが、プログラムを実行すると:./m mat1.txt mat2.txt 20 20 20 20(ファイル名とすべてのマトリックスの行と列の数)、次のエラーが発生します:セグメンテーション違反(コアダンプ)。問題は、ファイル結果の作成または書き込みにあります。手伝ってもらえますか?コードを以下に示します。

 /* Memory management */
mem_mat1 = (int *) malloc(M1 * N1 * sizeof(int));
if (mem_mat1 == NULL) {
    fprintf(stderr,"Error: malloc mem_mat1\n");
    /*MPI_Finalize();*/
    return (3);
}

mat1 = (int **) malloc(M1 *sizeof(int *));
if (mat1 == NULL) {
    fprintf(stderr,"Error: malloc mat1\n");
    /*MPI_Finalize();*/
    return (3);
} 

for (i=0; i<M1; i++) {
    mat1[i] = mem_mat1+(i*N1);
}

mem_mat2 = (int *) malloc(M2 * N2 * sizeof(int));
if (mem_mat2 == NULL) {
    fprintf(stderr,"Error: mem_mat2\n");
    /*MPI_Finalize();*/
    return (3);
}

mat2 = (int **) malloc(M2 *sizeof(int *));
if (mat2 == NULL) {
    fprintf(stderr,"Error: malloc mat2\n");
    /*MPI_Finalize();*/
    return (3);
} 

for (i=0; i<M2; i++) {
    mat2[i] = mem_mat2+(i*N2);
}

mem_matR = (int *) malloc(M1 * N2 * sizeof(int));
if (mem_matR == NULL) {
    fprintf(stderr,"Error: malloc mem_matR\n");
    /*MPI_Finalize();*/
    return (3);
}

matR = (int **) malloc(M1 *sizeof(int *));
if (matR == NULL) {
    fprintf(stderr,"Error: malloc matR\n");
    /*MPI_Finalize();*/
    return (3);
}

for (i=0; i<M1; i++) {
    matR[i] = mem_matR+(i*N2);
}

/* SEQUENTIAL PRODUCT MATRIX */

/*Open and Read file 1: mat1.txt*/
fmat1 = fopen(argv[1],"rb");
fread(mat1, M1 *sizeof(int *), N1 *sizeof(int *), fmat1);

/*Open and Read file 2: mat2.txt*/
fmat2 = fopen(argv[2],"rb");
fread(mat2, M2 *sizeof(int *), N2 *sizeof(int *), fmat2);

/*Create a file to write the result fmatR.txt*/
fdR = creat("matR.txt", "w");
if (fdR < 0) {
    fprintf(stderr, "Error create result file\n");
    return(2);
}

for (i=0;i<M1;i++) {
    for (j=0;j<N2;j++) {
        sum=0;
        for (k=0;k<N1;k++) {
            sum+=mat1[i][k]*mat2[k][j];
            matR[i][j]=sum;
        }
    }
 }
 write(fdR, &matR, M1*N2 *sizeof(int));
4

1 に答える 1

1

I think you're doing some mess with matR writing random memory... also the last line is wrong.

Fix:

1) take away mem_matR and all the code related to it

2) let matR be a pointer to the first element of the matrix (your buffer) and let it be a simple one dimension array of M1xN2 elements

matR = (int *) malloc( M1 * N2 * sizeof(int));

3) in the for loop at the end write matR this way

matR[j+i*N2]=sum;

4) finally save the data this way

write(fdR, (void *) matR, M1*N2 *sizeof(int));

--

also I think the fread calls are wrong (even if this doesn't cause issues)

fread(mat1, M1 *sizeof(int *), N1 *sizeof(int *), fmat1);

if I understand you have a martix of M1 x N1 elements that are integer. so...

fread(mat1, sizeof(int *), M1 * N1, fmat1);

same applies to the secon call

于 2013-01-02T16:50:53.280 に答える