【发布时间】:2013-01-02 16:14:20
【问题描述】:
我正在尝试使用 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));
【问题讨论】:
-
段错误在哪里?您采取了哪些措施来缩小或隔离它?
-
首先,从
malloc()..移除演员表 -
欢迎来到 SO。 Please read the FAQ。这不是调试服务。如果要调试,请使用调试器。
-
首先
creat的第二个参数不对,应该是O_WRONLY。 -
其他提示:您没有检查来自
fopen、fread或write的返回。您可能会发现perror()对错误报告很有用。
标签: c file-io segmentation-fault malloc matrix-multiplication