【发布时间】:2012-03-29 14:01:00
【问题描述】:
运行此代码时出现分段错误。有谁知道为什么?谢谢。
#include <stdio.h>
int main()
{
double **m1, **m2, **mr;
int m1_rows, m1_cols, m2_rows, m2_cols, mr_rows, mr_cols;
int i, j, k;
printf("Enter number of rows for matrix 1: ");
scanf("%d", &m1_rows);
printf("Enter number of columns for matrix 1: ");
scanf("%d", &m1_cols);
printf("Enter number of rows for matrix 2: ");
scanf("%d", &m2_rows);
printf("Enter number of columns for matrix 2: ");
scanf("%d", &m2_cols);
//allocate memory for matrix 1 m1
m1 = (double **) calloc(m1_rows, sizeof(double *));
for (i = 0; i < m1_rows; i++) {
m1[i] = (double *) calloc(m1_cols, sizeof(double));
}
//allocate memory for matrix 2 m2
m2 = (double **) calloc(m2_rows, sizeof(double *));
for (i = 0; i < m2_rows; i++) {
m2[i] = (double *) calloc(m2_cols, sizeof(double));
}
//allocate memory for sum matrix mr
mr = (double **) calloc(mr_rows, sizeof(double *));
for (i = 0; i < mr_rows; i++) {
mr[i] = (double *) calloc(mr_cols, sizeof(double));
}
//assign mr_rows and mr_cols
mr_rows = m1_rows;
mr_cols = m2_cols;
//initialize product matrix
for (i = 0; i < m1_rows; i++) {
for (j = 0; j < m2_cols; j++) {
mr[i][j] = 0;
}
}
//perform matrix multiplication
for (i = 0; i < m1_rows; i++) {
for (j = 0; j < m2_cols; j++) {
mr[i][j] = 0;
for (k = 0; k < m1_cols; k++) {
mr[i][j] += m1[i][k] * m2[k][j];
}
}
}
//print result
for (i = 0; i < mr_rows; i++) {
for (j = 0; j < mr_cols; j++) {
printf("%f\t", mr[i][j]);
}
}
//free memory m1
for (i = 0; i < m1_rows; i++); {
free(m1[i]);
}
free(m1);
//free memory m2
for (i = 0; i < m2_rows; i++); {
free(m2[i]);
}
free(m2);
//free memory mr
for (i = 0; i < mr_rows; i++); {
free(mr[i]);
}
free(mr);
return 0;
}
我使用 valgrind valgrind --tool=memcheck a.out 运行以获取有关分段错误的更多信息,但结果超过 30000 个错误,因此没有打印出来。
【问题讨论】:
-
在 GDB 中运行它以识别行。然后修复它。然后修复 30000 Valgrind 错误。然后继续开发。
-
@OliCharlesworth 其实我建议先阅读代码来调试它。这应该始终是方法的第一线,而不是使用工具。这样才能获得洞察力。
-
@DavidHeffernan:也许在一个 30 行的应用程序上。我不会目视检查 10000 行代码库来找出发生段错误的位置......
-
@OliCharlesworth 不,当然不是。我想我正专注于这个特定的问题。
标签: c segmentation-fault dynamic-memory-allocation matrix-multiplication